542. 01 Matrix

问题:

给定一个由 0 和 1 构成的二维数组。

求每个cell到最近0的距离。

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.

  

解法:BFS

思想:将所有 0 的cell加入queue

然后向四周蔓延,遍历完整个数组。

每蔓延一层,距离+1

层数即是queue的遍历level。

 

代码参考:

 1 class Solution {
 2 public:
 3     int m,n;
 4     vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
 5         n=matrix.size();
 6         if(n==0) return matrix;
 7         m=matrix[0].size();
 8         vector<int> dir={1,0,-1,0,1};
 9         vector<vector<int>> res(n, vector<int>(m,0));
10         vector<vector<bool>> visited(n, vector<bool>(m,false));
11         queue<pair<int, int>> q;
12         for(int i=0; i<n; i++) {
13             for(int j=0; j<m; j++) {
14                 if(matrix[i][j]==0) {
15                     q.push({i,j});
16                     visited[i][j]=true;
17                 }
18             }
19         }
20         int cur_i, cur_j;
21         int x, y;
22         int level = 0;
23         while(!q.empty()) {
24             int sz = q.size();
25             level++;
26             for(int i=0; i<sz; i++) {
27                 cur_i = q.front().first;
28                 cur_j = q.front().second;
29                 q.pop();
30                 for(int j=1; j<5; j++) {
31                     x=cur_i+dir[j-1];
32                     y=cur_j+dir[j];
33                     if(x<0 || y<0 || x>=n || y>=m || visited[x][y]) continue;
34                     res[x][y]=level;
35                     q.push({x,y});
36                     visited[x][y] = true;
37                 }
38             }
39         }
40         return res;
41     }
42 };

 

posted @ 2021-03-04 15:02  habibah_chang  阅读(64)  评论(0)    收藏  举报