给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
思路就是简单的bfs,首先是值为0的入队,然后每次取出队列第一个元素,更新四个方向,如果当前距离+1小于原距离,就将原距离更新即可。
注意Java中队列,offer()是添加元素,poll()取出第一个元素并删除,size()判断队列内元素,peek()查看第一个元素。
此外注意一下二维数组判断行列距离的方法。
class Solution {
int dirx[] = {0,0,1,-1};
int diry[] = {1,-1,0,0};
public int[][] updateMatrix(int[][] matrix) {
Queue<Integer>q = new LinkedList<Integer>();
//取行列大小的方法
int rowlen = matrix.length;
int collen = matrix[0].length;
int ans[][] = new int [rowlen][collen];
for(int i=0;i<rowlen;i++)
{
for(int j=0;j<collen;j++)
{
if(matrix[i][j]==0)
{
ans[i][j] = 0;
q.offer(i*collen+j);
}
else
{
ans[i][j] = 0x3f3f3f3f;//初始化为无穷大
}
}
}
while(q.size()>0)
{
int now = q.poll();
int x = now/collen;
int y = now%collen;
for(int i=0;i<=3;i++)
{
//遍历四个方向
int next_x = x+dirx[i];
int next_y = y+diry[i];
if(next_x<0||next_x>=rowlen||next_y<0||next_y>=collen)
{
continue;
}
if(ans[next_x][next_y]<0x3f3f3f3f)
{
continue;
}
if(ans[next_x][next_y] > ans[x][y]+1)
{
ans[next_x][next_y] = ans[x][y]+1;
q.offer(next_x*collen+next_y);
}
}
}
return ans;
}
}