1.解析
題目大意,求解矩陣中每個位置和離它最近的0之間的距離。
2.分析
我剛開始想到的是DFS,但我沒有去實現,參考Grandyang的思路。其實,求距離用BFS是比較合理的,像經典的迷宮問題,都是從一端探索到另外一端。而這裏,是有多個入口的。題目求解矩陣中'1'所處的位置跟離它最近的0之間的距離,所以我們以每個0所處的位置作爲需要探索的起點,放在隊列當中;若矩陣中的元素值爲1,則初始化爲INT_MAX。若當前探索的座標越界或者此時當前的距離小於或等於當前探索的點的值+1,則說明當前的值是最優值,無需更新。
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
queue<pair<int, int>> points;
for (int i = 0; i < m; ++i){
for (int j = 0; j < n; ++j){
if (matrix[i][j] == 0) points.push({i, j});
else matrix[i][j] = INT_MAX;
}
}
vector<vector<int>> moves{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; //左上右下
while (!points.empty()){
pair<int, int> point = points.front();
points.pop();
for (auto move : moves){
int x = point.first + move[0];
int y = point.second + move[1];
if (x < 0 || x >= m || y < 0 || y >= n ||
matrix[x][y] <= matrix[point.first][point.second] + 1)
continue; //越界或者大於當前的最小值
matrix[x][y] = matrix[point.first][point.second] + 1; //更新當前值
points.push({x, y});
}
}
return matrix;
}
};