题目链接:
https://leetcode.com/problems/01-matrix/description/#
题目大意:
给定一个只有0和1的二维数组,找到 每个值为1的元素离值为0的元素的最近距离(相邻格距离为1)
样例:
input:
0 0 0
0 1 0
1 1 1
output:
0 0 0
0 1 0
1 2 1
思路:
解决方法就是BFS。因为BFS每一步的代价都是相同的,所以BFS处理得到的结果必然是最短距离。下面是具体方法:
- 复制原数组,将值为0的元素放入队列中,并在数组中对值为1的元素改为-1,表示未遍历的点
- 每次弹出队列的头部a,判断a周围的格子是否是合法点(不越界)以及是否是未遍历的点,如果都是,则其值 = a的值 + 1
- 重复2,直到队列为空
代码:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>> &vmatrix) {
vector<vector<int>> matrix = vmatrix;
if(!vmatrix.size() ) return vmatrix;
int row = matrix.size();
int col = matrix[0].size();
typedef pair<int, int> pr;
queue<pr> q;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(matrix[i][j] != 0)
matrix[i][j] = -1;
else
q.push(pr(i,j));
}
}
pr d[4] = {pr(1,0),pr(0,1),pr(-1,0),pr(0,-1)};
while(q.size()) {
pr currentPoint = q.front();
q.pop();
int x = currentPoint.first;
int y = currentPoint.second;
for(int i = 0;i < 4; i++) {
int nextX = d[i].first + x;
int nextY = d[i].second + y;
if(nextX < row && nextX >= 0 && nextY >= 0 && nextY < col && matrix[nextX][nextY] == -1) {
matrix[nextX][nextY] = matrix[x][y] + 1;
q.push(pr(nextX,nextY));
}
}
}
return matrix;
}
};