剑指offer 专项突破版 107、矩阵中的距离

题目链接

思路
  • 一般而言找最短距离 要先考虑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;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值