542. 01 矩阵

作者: 莫小鹏 | 来源:发表于2018-10-12 17:40 被阅读0次

题目描述

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1:
输入:

0 0 0
0 1 0
0 0 0

输出:

0 0 0
0 1 0
0 0 0

示例 2:
输入:

0 0 0
0 1 0
1 1 1

输出:

0 0 0
0 1 0
1 2 1

注意:

给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。

分析

采用BFS算法
第一步,遍历矩阵,所有的0值都可能是起点,保存到队列,非0值设置成INT_MAX
第二步,遍历队列,取队列头的点,x, y。判断上、下、左、右的点,如果大于matrix[x][y] + 1,则更新这些点的数值,并把更新后的点放进队列里面,因为这些点更新了,这些点周围的点也可能需要更新

代码

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        queue<pair<int,int>> q;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(matrix[i][j] == 0) {
                    q.push(make_pair(i, j));
                } else {
                    matrix[i][j] = INT_MAX;
                }
            }
        }
        
        while(!q.empty()){
            auto p = q.front();
            int x = p.first;
            int y = p.second;
            q.pop();
            int cur = matrix[x][y] + 1;
            if(x > 0 && matrix[x - 1][y] > cur) {
                matrix[x-1][y] = cur;
                q.push(make_pair(x - 1, y));
            }
            if(x < row - 1 && matrix[x + 1][y] > cur) {
                matrix[x + 1][y] = cur;
                q.push(make_pair(x + 1, y));
            }
            if(y > 0 && matrix[x][y - 1] > cur) {
                matrix[x][y - 1] = cur;
                q.push(make_pair(x, y - 1));
            }
            if(y < col - 1 && matrix[x][y + 1] > cur) {
                matrix[x][y + 1] = cur;
                q.push(make_pair(x, y + 1));
            }
        }
        return matrix;
    }
};

题目链接

https://leetcode-cn.com/problems/01-matrix/description/

相关文章

  • LeetCode 542. 01 矩阵

    542. 01 矩阵 题目来源:https://leetcode-cn.com/problems/01-matri...

  • 542. 01 矩阵

    题目描述 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。 两个相邻元素间的距离为 1 。 ...

  • 542. 01矩阵

    题目描述 给定一个由0和1组成的矩阵,找出每个元素到最近0的距离,相邻元素间的距离为1。例如:输入 输出 注意: ...

  • 542. 01矩阵(Python)

    题目 难度:★★☆☆☆类型:数组方法:二分法 力扣链接请移步本题传送门[https://leetcode-cn.c...

  • LeetCode:01矩阵

    542. 01 矩阵 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。两个相邻元素间的距离为...

  • ARTS打卡第一周

    ARTS打卡第一周 Algorithm:每周至少做一个 leetcode 的算法题 542. 01 矩阵 Revi...

  • 542. 01 Matrix

    Given a matrix consists of 0 and 1, find the distance of ...

  • 542. 01 Matrix

    这道题不看答案,没想出思路,做题还是不够,看了bfs的思路,然后手写了一遍,记录一下。这道题从bfs的角度来看,思...

  • [Java] 542. 01 Matrix

    Description Given a matrix consists of 0 and 1, find the ...

  • 542. 01 矩阵、1162. 地图分析、994. 腐烂的橘子

    本次的三道题都用了多源点BFS的方法,关于什么是多源点BFS呢,就是求很多个起点到一个终点的关系,就将终点入队,反...

网友评论

    本文标题:542. 01 矩阵

    本文链接:https://www.haomeiwen.com/subject/xpbgaftx.html