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 righ
题目分析
给一个由0和1组成的矩阵,求每一个元素到0元素的最近距离。
考虑用BFS,用队列实现:
1.将矩阵中为1的元素入队que,并设初始距离step=0
2.若que不为空,循环:
step = step +1
遍历队列中的元素,这里用num计数实现,若在上下左右其中一个方向存在为0的元素:
当前元素对应坐标的距离等于step,将元素入另一个队列delQue
遍历队列delQue:
取元素坐标(x,y),令matrix[x][y] =0;
c++实现:
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int m = matrix.size(),n = matrix[0].size();; int step = 0; int dx[4] = {0, 0, -1, 1}; int dy[4] = {1, -1, 0, 0}; vector<vector<int>> distance(m, vector<int>(n, 0)); queue<pair<int, int>> que; for (int i=0; i<m;i++) { for (int j=0;j<n;j++) { if (matrix[i][j] == 1) { que.push(make_pair(i,j)); } } } int x, y, tmp_x, tmp_y; while(!que.empty()) { step ++; queue<pair<int, int>> delQue; //遍历queue int num = que.size(); while (num--) { x = que.front().first; y = que.front().second; //先删除元素 que.pop(); bool flag = true; for (int i = 0;i < 4 ;i++) { tmp_x = dx[i] + x; tmp_y = dy[i] + y; if(tmp_x >=0 && tmp_x <m && tmp_y >=0 && tmp_y < n && matrix[tmp_x][tmp_y] == 0) { distance[x][y] = step; delQue.push(make_pair(x,y)); flag = false; break; } } //周围没有为0元素,当前元素入队尾,进入下次que循环使用 if(flag) { que.push(make_pair(x,y)); } } while(!delQue.empty()) { matrix[delQue.front().first][delQue.front().second] = 0; delQue.pop(); } } return distance; } };