542. 01 Matrix
https://www.cnblogs.com/grandyang/p/6602288.html
将所有的1置为INT_MAX,然后用所有的0去更新原本位置为1的值。
最短距离肯定使用bfs。
每次更新了值的地方还要再加入队列中 。
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int m = matrix.size(),n = matrix[0].size(); queue<pair<int,int>> q; for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ if(matrix[i][j] == 0) q.push(make_pair(i,j)); else matrix[i][j] = INT_MAX; } } while(!q.empty()){ auto coordinate = q.front(); q.pop(); int x = coordinate.first,y = coordinate.second; for(auto dir : dirs){ int new_x = x + dir[0]; int new_y = y + dir[1]; if(new_x < 0 || new_x >= matrix.size() || new_y < 0 || new_y >= matrix[0].size() || matrix[new_x][new_y] <= matrix[x][y] + 1) continue; matrix[new_x][new_y] = matrix[x][y] + 1; q.push(make_pair(new_x,new_y)); } } return matrix; } private: vector<vector<int>> dirs{{-1,0},{1,0},{0,-1},{0,1}}; };
原文:https://www.cnblogs.com/ymjyqsx/p/10946613.html