leetcode 994.腐烂的橘子【BFS】

使用队列对矩阵进行广度优先搜索:
建立Orange类保存每个腐烂橘子的节点信息,包括该节点腐烂所需要的分钟数。

  1. 遍历矩阵,将腐烂的橘子放入队列;
  2. 遍历队列,判断每个腐烂橘子上下左右的位置是否有新鲜橘子,有则将其腐烂病放入队列;
  3. 遍历矩阵,判断是否还存在新鲜橘子,若存在则返回-1,否则返回minute。
class Solution {
    class Orange{
        int x, y, minute;
        public Orange(int _x, int _y, int _minute){
            x = _x;
            y = _y;
            minute = _minute;
        }
    }
    
    static int[][] dir ={{-1,0},{1,0},{0,-1},{0,1}}; 
    
    public int orangesRotting(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        int minute = 0;
        Queue<Orange> queue = new LinkedList<>();
        
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(grid[i][j] == 2)
                    queue.add(new Orange(i, j, minute));
            }
        }
        
        while(!queue.isEmpty()){
            Orange temp = queue.poll();
            minute = temp.minute;
            for(int k=0; k<4; k++){
                int newX = temp.x+dir[k][0];
                int newY = temp.y+dir[k][1];
                if(newX>=0 && newX<row && newY>=0 && newY<col && grid[newX][newY] == 1){
                    grid[newX][newY] = 2;
                    queue.add(new Orange(newX, newY, temp.minute+1));
                }
            }
        }
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(grid[i][j] == 1)
                    return -1;
            }
        }
    
        return minute;
        
    }
}


发布了55 篇原创文章 · 获赞 0 · 访问量 794

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/104652414