思路:和地图分析这道题一模一样的思路。
一轮一轮的扩张。
class Solution {
public:
struct point
{
int x;
int y;
point(int xx, int yy) :x(xx), y(yy) {}
};
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
queue<point>myqueue;
for (int i = 0; i < matrix.size(); i++)
for (int j = 0; j < matrix[0].size(); j++)
{
if (matrix[i][j] == 1)matrix[i][j] = -1;
if (matrix[i][j] == 0)myqueue.push(point(i, j));
}
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
int count = 0;//扩张的轮数
while (!myqueue.empty())
{
point p = myqueue.front();
myqueue.pop();
count = matrix[p.x][p.y];
for (int i = 0; i < 4; i++)
{
int new_x = p.x + dx[i];
int new_y = p.y + dy[i];
if (new_x >= 0 && new_x < matrix.size() && new_y >= 0 && new_y < matrix[0].size())
{
if (matrix[new_x][new_y] == -1)
{
matrix[new_x][new_y] = count + 1;
myqueue.push(point(new_x, new_y));
}
}
}
}
return matrix;
}
};