LeetCode 算法入门 Day9 广度优先搜索 / 深度优先搜索 Java

542. 01 矩阵

问题描述:

代码:

class Solution {
        int d[][]={{0,1},{1,0},{-1,0},{0,-1}};
    public int[][] updateMatrix(int[][] mat) {
        Queue<int[]> queue = new LinkedList<int[]>();
        int n=mat.length,m=mat[0].length;
        Boolean isZero[][]=new Boolean[n][m];
        int dist[][]=new int[n][m];
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(mat[i][j]==0){
                    queue.offer(new int[]{i, j});
                    isZero[i][j]=true;
                }else{
                    isZero[i][j]=false;
                }
            }
        }
        while(!queue.isEmpty()){
                int cell[]=queue.poll();
               int x=cell[0],y=cell[1];
                for(int ii=0;ii<4;ii++){
                    int xx=x+d[ii][0];
                    int yy=y+d[ii][1];
                    if(xx>=0 && xx<n && yy>=0 && yy<m && !isZero[xx][yy]){
                         
                          {
                             dist[xx][yy]=dist[x][y]+1;
                            queue.offer(new int[]{xx,yy});
                            isZero[xx][yy]=true;
                          }  
                    }
                }
                
            
    
        }
        return dist;
    }
}

 思路:

 

 

 

 994. 腐烂的橘子

问题描述:

 代码:

class Solution {
    static int dir[][]={{0,1},{1,0},{-1,0},{0,-1}};
    public int orangesRotting(int[][] grid) {
        int n=grid.length,m=grid[0].length;
        Queue<int[]> queue = new LinkedList<int[]>();
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]==2){
                    queue.offer(new int[]{i,j});
                }
            }
        }
        int sum=0;
        int ss=queue.size();
        while(!queue.isEmpty()){
            if(ss==0)
                {
                    sum++;
                    ss=queue.size();
                }
            int cell[]=queue.poll();
            int x=cell[0],y=cell[1];
            for(int index=0;index<4;index++){
                int dx=x+dir[index][0];
                int dy=y+dir[index][1];
                if(dx>=0 && dx<n && dy>=0 && dy<m && grid[dx][dy]==1){
                    grid[dx][dy]=2;
                    queue.offer(new int[]{dx,dy});
                }
                
            }
            ss--;
        }
         for(int ii=0;ii<n;ii++){
            for(int jj=0;jj<m;jj++){
                if(grid[ii][jj]==1){
                    return -1;
                }
            }
        }
        return sum;

    }
}

思路:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值