一、题目描述
原题描述————————-原题链接
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.
Note:
1) The number of elements of the given matrix will not exceed 10,000.
2) There are at least one 0 in the given matrix.
3) The cells are adjacent in only four directions: up, down, left and right.
给定一个0-1矩阵,输入保证至少有一个零,返回每个位置距离0的最短路径的新矩阵,如下例:
输入
0 0 0
0 1 0
1 1 1
输出
0 0 0
0 1 0
1 2 1
注意,其中“2”这个结果可以由①向上走一步②再向左 或 向右 或 向上 走一步达到“0”得到距离2。
二、题目分析
利用队列解决问题,在原来输入矩阵的基础上,进行处理,得到输出的距离矩阵
①遍历该0-1矩阵
a、对应位置值为0,记录 下标{pos.row,pos.col} 并将之放在队列中,由于0距离本身的距离是0,所以输出矩阵该位置的距离记录为0,可以不变
b、对应位置值为1,将之变为10000(该题不会出现的一个距离),用作初始距离
②当队列不为空的时候
a、对于队列当中每个下标位置集合{pos.row,pos.col},该下标可以向题目中的上右下左方向走,每走一步,在原来的值matrix[pos.row][pos.col]基础上+1。
b、当上面的值的更新发生之后,要相应的将更新的值的位置进行入队操作。
三、源代码(C++)
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<vector<int> > updateMatrix(vector<vector<int> >& matrix) {
int row_size = matrix.size();
if(row_size == 0)
return matrix;
int col_size =matrix[0].size();
queue<vector<int> > q;
for(int i = 0; i < row_size; i ++)
for(int j = 0; j < col_size; j ++)
if(matrix[i][j] == 0)
{
vector<int> v;
v.push_back(i);
v.push_back(j);
q.push(v);
}
else
matrix[i][j] = 10000;
int destination[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};//上右下左的方向
while(!q.empty())
{
vector<int> pos = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int row = pos[0] + destination[i][0];
int col = pos[1] + destination[i][1];
if(row < 0 || row > row_size - 1 || col < 0 || col > col_size - 1 ||
matrix[row][col] < matrix[pos[0]][pos[1]] + 1)
continue;
matrix[row][col] = matrix[pos[0]][pos[1]] + 1;
vector<int> v;
v.push_back(row);
v.push_back(col);
q.push(v);
}
}
return matrix;
}
int main()
{
/*
{{0, 0, 0},
{0, 1, 0},
{1, 1, 1}}
{ {0, 0, 0},
{0, 1, 0},
{0, 0, 0}}
*/
int a[3][3] = {{0, 0, 0},
{0, 1, 0},
{1, 1, 1}};
vector<vector<int> > matrix;
for(int i = 0; i < 3; i ++)
{
vector<int> row;
for(int j = 0; j < 3; j ++)
row.push_back(a[i][j]);
matrix.push_back(row);
}
vector<vector<int> > result = updateMatrix(matrix);
for(int i = 0; i < result.size(); i ++)
{
for(int j = 0; j < result[i].size(); j ++)
cout << result[i][j] << " ";
cout << endl;
}
}