542. 01 Matrix
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.Example 1:
Input:
0 0 0 0 1 0 0 0 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
0 0 0 0 1 0 1 2 1
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
2、从0扩散出去找1.
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
queue<pair<int, int>> que;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
if (matrix[i][j] == 1)
matrix[i][j] = -1;
else
que.push(make_pair(i, j));
}
int a[4] = {0, 1, 0, -1};
int b[4] = {1, 0, -1, 0};
int distance = 1;
while (!que.empty())
{
int size = que.size();
for (int i = 0; i < size; i++)
{
int x = que.front().first, y = que.front().second;
que.pop();
for (int k = 0; k < 4; k++)
{
int _x = x + a[k], _y = y + b[k];
if (isvaild(_x, _y, row, col) && matrix[_x][_y] == -1)
{
matrix[_x][_y] = distance;
que.push(make_pair(_x, _y));
}
}
}
distance++;
}
return matrix;
}
bool isvaild(int x, int y, int row, int col) {
return x >= 0 && x < row && y >= 0 && y < col;
}
};