题目链接
思路
- 一般而言找最短距离 要先考虑BFS
- 这道题应该是0找1
- 首先我们把所有的0顶点放入队列 然后依次出队 把所有相邻的1顶点放入另一个队列
- 那么此时第二个队列的所有的顶点距离都是1 然后再把和第二个队列相邻的所有的1顶点放入第三个队列。。。
- 注意要放入队列还有一个条件 就是我们如果成功通过0顶点更新了1顶点的距离的话 那就把改1顶点放入队列
if(result[pos[0]][pos[1]] + 1 < result[x][y]){
result[x][y] = result[pos[0]][pos[1]] + 1;
queue1.offer(new int[]{x,y});
}
- 也就是说 只有某一个1顶点距离更新了 才会用它去通知所有和他相邻的顶点
class Solution {
public int[][] updateMatrix(int[][] mat) {
int[][] result = new int[mat.length][mat[0].length];
Queue<int[]> queue1 = new LinkedList<>() , queue2 = new LinkedList<>();
for(int i = 0 ; i < mat.length ; i++){
for(int j = 0 ; j < mat[i].length ; j++){
if(0 == mat[i][j]){
queue1.add(new int[]{i,j});
result[i][j] = 0;
}
else result[i][j] = Integer.MAX_VALUE;
}
}
int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
while(!queue1.isEmpty()){
int[] pos = queue1.poll();
for(int[] dir : dirs){
int x = dir[0] + pos[0] , y = dir[1] + pos[1];
if(x >=0 && x < mat.length && y >=0 && y < mat[0].length){
if(result[pos[0]][pos[1]] + 1 < result[x][y]){
result[x][y] = result[pos[0]][pos[1]] + 1;
queue1.offer(new int[]{x,y});
}
}
}
}
return result;
}
}