1 题目: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
2 solution
从起点开始广度优先搜索。
代码
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
/*
* 广度优先
*/
int m = mat.size();
int n = mat[0].size();
vector<vector<int>> res(m, vector<int>(n, -1));
queue<int> x;
queue<int> y;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0) {
res[i][j] = 0;
x.push(i);
y.push(j);
}
}
}
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
while (!x.empty()) {
int r = x.front();
int c = y.front();
x.pop(), y.pop();
for (int i = 0; i < 4; i++) {
int rr = r + dx[i];
int cc = c + dy[i];
if (rr < 0 || rr >= m || cc < 0 || cc >= n || res[rr][cc] != -1) continue;
res[rr][cc] = res[r][c] + 1;
x.push(rr);
y.push(cc);
}
}
return res;
}
};