Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
大致题意
找到矩阵中每个1最近的0的距离
题解
题目类型:BFS、DFS
这道题可以采用每到一个非0节点就深搜一次,比对所有深搜结果,取路径最短的做法,但其中浪费了不少的子问题,有些节点可以利用其他节点计算的结果求出距离。
这里采用BFS,每层BFS表示的距离+1,可以一次完整搜索解决整个距离问题。
过程:将所有0节点加入队列,开始BFS,每层BFS+1的距离,向四周查找(查找过的不再查找)
代码如下
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& A) {
vector<vector<int> > ans;
queue<pair<int, int> > Q;
const int D[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
int n, m, row, col, i, j;
pair<int, int> u;
n = A.size();
m = A[0].size();
ans.resize(n);
for (i=0; i<n; i++) ans[i].resize(m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
if (A[i][j] == 0) {
Q.push(make_pair(i, j));
ans[i][j] = 0;
}
else ans[i][j] = -1;
while (!Q.empty()) {
u = Q.front();
Q.pop();
for (i=0; i<4; i++) {
row = u.first + D[i][0];
col = u.second + D[i][1];
if (row >= 0 && row < n && col >= 0 && col < m && ans[row][col] == -1) {
ans[row][col] = ans[u.first][u.second] + 1;
Q.push(make_pair(row, col));
}
}
}
return ans;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。