您的位置:首页 > 其它

leetcode 542. 01 Matrix

2018-01-11 10:40 302 查看
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 0

Output:
0 0 0
0 1 0
0 0 0


Example 2: 

Input:
0 0 0
0 1 0
1 1 1

Output:
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.

1、标准BFS
2、从1扩散出去找0.

class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix)
{
int row = matrix.size();
int col = matrix[0].size();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (matrix[i][j] != 0) //开始扩散找0
{
BFS(matrix, i, j, row, col);
}
}
}

return matrix;
}
private:
void BFS(vector<vector<int>>& matrix, int i, int j, int row, int col)
{
queue<pair<int, int>> que;
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 k = 0; k < size; k++)
{
int x = que.front().first, y = que.front().second;
que.pop();
for (int t = 0; t < 4; t++)
{
int _x = x + a[t], _y = y + b[t];
if (isvaild(_x, _y, row, col))
{
if (matrix[_x][_y] == 0) //说明找到了0
{
matrix[i][j] = distance;
return;
}
else
que.push(make_pair(_x, _y));
}
}
}
distance ++;
}
}

bool isvaild(int x, int y, int row, int col)
{
return x >= 0 && x < row && y >= 0 && y < col;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: