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;
}
};