这个题需要到时候再看一下,涉及好几点。
(1)一个是问题的转化,把1到0的最短距离化成0到1的最短距离。
(2)初始化工作,上来先求行数和列数,然后初始化结果矩阵。
(3)pair<int,int>的使用。并且定义用pair初始化四个方向。
(4)BFS的具体内部实现和细节。
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int rows = matrix.size();
int clos = matrix[0].size();
vector<vector<int>> ret = matrix;
typedef pair<int, int> point;
queue<point> q;
for (int i=0; i<rows; i++) {
for (int j=0; j<clos; j++) {
if (matrix[i][j] == 0){
ret[i][j] = 0;
q.push(point(i,j));
}
else
ret[i][j] = -1;
}
}
point d[4] = {point(-1,0),point(1,0),point(0,-1),point(0,1)};//这种在矩阵中移动的问题,可以事先定义好四个元素代表四个移动的方向
while (q.size()) {
point temp = q.front();
q.pop();
int x = temp.first;
int y = temp.second;
for (int i=0; i<4; i++) {
int xx = x + d[i].first;
int yy = y + d[i].second;
if (xx>=0 && xx<rows && yy>=0 && yy<clos && ret[xx][yy]==-1) {// 里面这个判断是核心,即必须是遇见非0元素才考虑更新结果矩阵
ret[xx][yy] = ret[x][y] + 1;
q.push(point(xx,yy));
}
}
}
return ret;
}
};