您的位置:首页 > 其它

[leetcode]542. 01 Matrix

2017-05-16 11:20 381 查看
题目链接: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


思路:这个求每一个单元格到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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: