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.
看到这个问题最自然的想法是对每个1使用广搜,搜到0时就终止,然后计算与这个0之间的距离。但这样的问题是,每次广搜中我都只能得出起点的1与0(终点)的距离,而无法得出搜索过程中经过的1与0的距离,因为我们必须要先知道起点与终点之间的距离,才能逆推出这些中间点与终点的距离。所以对1使用广搜的话有点浪费,每次搜索都只能求出一个距离。
于是我转而考虑对每个0进行广搜会不会更好。从0开始广搜,每经过一个1,就计算它们之间的距离,如果当前距离小于之前求出的最小距离,就更新最小距离;如果经过的是0,就忽略。实际上,应该只有与1相邻的0才会开始广搜。这样,每次进行广搜时,可以求出多个0与1之间的距离。
这两种广搜方法效率不同的原因在于,题目是求每个元素到0的最短距离,关键是要知道“0”在哪里。从1开始广搜,一开始不知道0在哪里,只有找到一个0才有可能更新最短距离。从0开始广搜,我们一开始就知道了0的位置,所以每走一步都可以更新最短距离。
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> d;
d.resize(n);
queue<pair<int, int> > q;
pair<int, int> p;
for(int i=0; i<n; i++) {
d[i].resize(m);
for(int j=0; j<m; j++) {
if(matrix[i][j] == 0) {
d[i][j] = 0;
q.push({i, j});
}
else d[i][j] = INT_MAX;
}
}
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};//上下左右四个方向
int newX, newY;
while(!q.empty()) {
p = q.front();
q.pop();
for(int i=0; i<4; i++) {
int newX = p.first + dir[i][0];
int newY = p.second + dir[i][1];
if(newX>=0 && newX<n && newY>=0 && newY<m && matrix[newX][newY]==1) {
if(d[p.first][p.second]+1 < d[newX][newY]) {
d[newX][newY] = d[p.first][p.second]+1;
q.push({newX, newY});
}
}
}
}
return d;
}
};
上面代码中,只有当前距离小于最小距离的“1”才会加入到搜索队列中,避免了走“回头路”重复搜索。