题目链接:https://leetcode.com/problems/01-matrix/#/description
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
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
// 初始化动态规划的数组,所有的距离值都设置为一个很大的数
vector<vector<int>> dist(m, vector<int>(n, INT_MAX / 2));
// 如果 (i, j) 的元素为 0,那么距离为 0
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
dist[i][j] = 0;
}
}
}
// 只有 水平向左移动 和 竖直向上移动,注意动态规划的计算顺序
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i - 1 >= 0) {
dist[i][j] = min(dist[i][j], dist[i - 1][j] + 1);
}
if (j - 1 >= 0) {
dist[i][j] = min(dist[i][j], dist[i][j - 1] + 1);
}
}
}
// 只有 水平向右移动 和 竖直向下移动,注意动态规划的计算顺序
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
if (i + 1 < m) {
dist[i][j] = min(dist[i][j], dist[i + 1][j] + 1);
}
if (j + 1 < n) {
dist[i][j] = min(dist[i][j], dist[i][j + 1] + 1);
}
}
}
return dist;
}
};
思路:这个求每一个单元格到0的最短路径问题。可以用广度优先(BFS)搜索进行求解。广度优先搜索一般使用队列实现。
1. 首先将matrix中元素为0的单元格坐标入队,其最短路径设置为0,将元素值为1的单元格的最短距离设置为-1.
2. 从队列中取出元素front,将其相邻未被访问且元素值为-1的最短路径设置为res[front]+1,并入队.
3. 循环,直到队列为空.
class Solution{
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix)
{
if(matrix.size()==0 || matrix[0].size()==0)
return matrix;
vector<vector<int>>res=matrix;
typedef pair<int,int> tp;
queue<tp> q;
for(int i=0;i<matrix.size();i++)
{
for(int j=0;j<matrix[0].size();j++)
{
if(matrix[i][j]==0)
q.push(tp(i,j));
else
res[i][j]=-1;
}
}
tp d[4]={tp(-1,0),tp(1,0),tp(0,1),tp(0,-1)};
while(q.size())
{
tp front=q.front();
int x=front.first,y=front.second;
q.pop();
for(int i=0;i<4;i++)
{
int nx=x+d[i].first,ny=y+d[i].second;
if(nx>=0 && nx<res.size() && ny>=0 && ny<res[0].size() && res[nx][ny]==-1)
{
res[nx][ny]=res[x][y]+1;
q.push(tp(nx,ny));
}
}
}
return res;
}
private:
vector<vector<int>> res;
};