542. 01 矩阵
给定一个由
0
和1
组成的矩阵mat
,请输出一个大小相同的矩阵,其中每一个格子是mat
中对应位置元素到最近的0
的距离。两个相邻元素间的距离为
1
。示例 1:
输入:mat = [[0,0,0],[0,1,0],[0,0,0]] 输出:[[0,0,0],[0,1,0],[0,0,0]]示例 2:
输入:mat = [[0,0,0],[0,1,0],[1,1,1]] 输出:[[0,0,0],[0,1,0],[1,2,1]]提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
mat
中至少有一个0
正难则反
很难从1出发去找每一个最近的0,这样就只能使用单源最短路径bfs求解,最终导致复杂度过高。所以可以将所有的0作为一个超级源点,把所有的起点加入队列,剩下的就都是1,然后利用这个队列进行bfs操作,每访问一个结点,就更新它的step步数值,并放入book标记数组里。
class Solution {
public:int m, n;typedef pair<int, int> PII;int dx[4] = {0, 0, 1, -1};int dy[4] = {1, -1, 0, 0};vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {m = mat.size(), n = mat[0].size();vector<vector<bool>> book(m, vector(n, false));queue<PII> q;1、将所有的 0 作为一个超级源点放入队列中for(int i = 0; i < m; i++){for(int j = 0; j < n; j++){if(mat[i][j] == 0){q.push({i, j});book[i][j] = true;}}}2、利用bfs操作更新所有值为1的结点int step = 0;while(q.size()){step++;int sz = q.size();while(sz--){auto [a, b] = q.front();q.pop();for(int k = 0; k < 4; k++){int x = a + dx[k];int y = b + dy[k];if(x >= 0 && y >= 0 && x < m && y < n && !book[x][y]){// if(mat[x][y] == 1) 0放入队列了,mat中只有1,无需判断直接处理即可mat[x][y] = step;book[x][y] = true;q.push({x, y});}}}}return mat;}
};