LEETCODE算法: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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//多元广度优先搜索,把所有为0的点加入到队列bfs即可,单源需要考虑的太多还容易超时。
class Solution {
static constexpr int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int row=matrix.size();
int line=matrix[0].size();
vector<vector<int>> vis(row,vector<int>(line));
vector<vector<int>> res(row,vector<int>(line));
queue<pair<int,int>> q;
for(int i=0;i<matrix.size();i++)
{
for(int j=0;j<matrix[i].size();j++)
{
if(matrix[i][j]==0){
q.push(make_pair(i,j));
vis[i][j]=1;
}
}
}
while(!q.empty())
{
auto tmp=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int x=tmp.first+d[i][0];
int y=tmp.second+d[i][1];
if(x<row&&y<line&&x>=0&&y>=0&&!vis[x][y])
{
q.push(make_pair(x,y));
res[x][y]=res[tmp.first][tmp.second]+1;
vis[x][y]=1;
}
}
}
return res;
}

};