LeetCode1162地图分析 和 LeetCode994腐烂的橘子

地图分析

在这里插入图片描述
bfs(填满整个表格)
在这里插入图片描述
代码:

class Solution {
    public int maxDistance(int[][] grid) {
        int[] dx={1,0,-1,0};
        int[] dy={0,1,0,-1};
        Queue<int[]> queue=new ArrayDeque<>();
        int len=grid.length;
        for(int i=0;i<len;i++)
            for(int j=0;j<len;j++){
                if(grid[i][j]==1)queue.offer(new int[]{i,j});
            }
        boolean hasOcean=false;
        int[] point =null;
        while(!queue.isEmpty()){
            point=queue.poll();
            int x=point[0],y=point[1];
            for(int i=0;i<4;i++){
                int newX=x+dx[i];
                int newY=y+dy[i];
                if (newX<0 ||newX>=len || newY<0 ||newY>=len || grid[newX][newY]!=0)continue;
                queue.offer(new int[]{newX,newY});
                grid[newX][newY]=grid[x][y]+1;
                hasOcean=true;
            }
        }
        if(point == null ||!hasOcean)return -1;
        return grid[point[0]][point[1]]-1;
    }
}

腐烂的橘子

在这里插入图片描述
代码:

class Solution {
 public static int orangesRotting(int[][] grid) {
        int[] dx={1,0,-1,0};
        int[] dy={0,1,0,-1};
        int m=grid.length;
        int n=grid[0].length;
        if(n==1 && m==1){
            if(grid[0][0]==0||grid[0][0]==2)return 0;
            else if(grid[0][0]==1)return -1;
        }
        Queue<int[]> queue=new ArrayDeque<>();
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++){
                if(grid[i][j]==2){
                    queue.offer(new int[]{i,j});
                }
            }
        //boolean has=false;
        int cnt=0;
        int[] point=null;
        while(!queue.isEmpty()){
            point=queue.poll();
            int x=point[0],y=point[1];
            for(int i=0;i<4;i++){
                int newX=x+dx[i];
                int newY=y+dy[i];
                if(newX<0 || newX>=m || newY<0 || newY>=n || grid[newX][newY]==0|| grid[newX][newY]>=2)continue;
                queue.offer(new int []{newX,newY});
                grid[newX][newY]=grid[x][y]+1;
            }
        }
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++){
                if(grid[i][j]==1){
                    return -1;
                }
            }
        return grid[point[0]][point[1]]-2;
    }
}

思路:

BFS广度优先遍历,保存一个或多个节点,对数组进行遍历。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值