1. 首页
  2. 软件开发
  3. day-24 腐烂的橘子

day-24 腐烂的橘子

  • 发布于 2024-09-26
  • 1 次阅读

思路:利用bfs的思想 首先利用bfs遍历值为2的橘子(遍历时1和2都可以走)结束后如果存在某个橘子未被访问过且值为1则返回-1 再利用bfs遍历值为2的橘子 每遍历一次 时间加1 注意不要立即将map的值变为2,可以通过一个缓存数组临时存放 这样即可确定腐烂时间

注意点:map=grid只是把指针给map map改变grid也会改变 map=new int[rows][cols]; map=grid map改变grid不会改变

code:

class Solution {

    public int dir[][]={
   {
   0,1},{
   0,-1},{
   1,0},{
   -1,0}};
    public int map[][];
    public int tmap[][];
    public boolean vis[][];
    public int cows;
    public int cols;
    public int num1=0;
    public int num2=0;
    public int orangesRotting(int[][] grid) {

        cows=grid.length;
        if(cows==0) return -1;
        cols=grid[0].length;
        map=new int[cows][cols];
        tmap=new int[cows][cols];
        for(int i=0;i<cows;i++){

            for(int j=0;j<cols;j++){

                map[i][j]=grid[i][j];
                tmap[i][j]=grid[i][j];
            }
        }
        vis=new boolean[cows][cols];
        int ans=0;
        for(int i=0;i<cows;i++){
   //判断是否存在不能腐烂的橘子
            for(int j=0;j<cols;j++){

                if(!vis[i][j]&&map[i][j]==2){

                    istrue(i,j);
                }
            }
        }
        boolean flag=true;
        for(int i=0;i<cows;i++){

            for(int j=0;j<cols;j++){

                if(!vis[i][j]&&map[i][j]==1){

                    flag=false;
                }
            }
        }
        if(flag==false)return -1;

        flag=true;
        while(flag){

            flag=false;
            for(int i=0;i<cows;i++){

                for(int j=0;j<cols;j++){

                    if(map[i][j]==1){
   //还存在新鲜橘子
                        flag=true;
                        break;
                    }
                }
                if(flag==true) break;
            }
            if(flag==false) break;//不存在新鲜橘子

            for(int i=0;i<cows;i++){

                for(int j=0;j<cols;j++){

                    if(map[i][j]==2){

                        bfs(i,j);
                    }
                }
            }
            ans++;
            for(int i=0;i<cows;i++){

                for(int j=0;j<cols;j++){

                    map[i][j]=tmap[i][j];
                }
            }
        }
        return ans;
    }

    public void bfs(int i,int j){

        for(int k=0;k<4;k++){

            int newi=i+dir[k][0];
            int newj=j+dir[k][1];
            if(0<=newi&&newi<cows&&0<=newj&&newj<cols&&
            tmap[newi][newj]==1){

                tmap[newi][newj]=2;//变为坏橘子
            }
        }
    }

    public void istrue(int i,int j){

        vis[i][j]=true;
        for(int k=0;k<4;k++){

            int newi=i+dir[k][0];
            int newj=j+dir[k][1];
            if(0<=newi&&newi<cows&&0<=newj&&newj<cols&&(
            map[newi][newj]==1||map[newi][newj]==2)&&!vis[newi][newj]){

                istrue(newi,newj);
            }
        }
    }
}

原文链接: https://blog.csdn.net/qq_53568730/article/details/136841133