994. 腐烂的橘子

public class Solution {
    public class Orange {// 橘子
        int x, y;// 横坐标,纵坐标

        public Orange(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public int orangesRotting(int[][] grid) {
        Queue<Orange> queue = new LinkedList<Orange>();
        Queue<Orange> queue1 = new LinkedList<Orange>();
        int level = 0;
        int visited[][] = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 2) {// 腐烂的
                    visited[i][j] = 2;// 腐烂的
                    queue.add(new Orange(i, j));
                } else if(grid[i][j] == 0) {// 空的
                    visited[i][j] = 0;// 空的
                } else {
                    visited[i][j] = 1;// 新鲜的
                }
            }
        }
        while (!queue.isEmpty()) {
            int x = queue.peek().x;
            int y = queue.poll().y;
            if (x - 1 > -1 && visited[x - 1][y] == 1) {
                visited[x - 1][y] = 2;
                queue1.add(new Orange(x - 1, y));
            }
            if (y - 1 > -1 && visited[x][y - 1] == 1) {
                visited[x][y - 1] = 2;
                queue1.add(new Orange(x, y - 1));
            }
            if (x + 1 < grid.length && visited[x + 1][y] == 1) {
                visited[x + 1][y] = 2;
                queue1.add(new Orange(x + 1, y));
            }
            if (y + 1 < grid[0].length && visited[x][y + 1] == 1) {
                visited[x][y + 1] = 2;
                queue1.add(new Orange(x, y + 1));
            }
            if (queue.isEmpty()) {
                if (!queue1.isEmpty()) {
                    while (!queue1.isEmpty()) {
                        queue.add(queue1.poll());
                    }
                    level += 1;
                }
            }
        }
        for (int i = 0; i < visited.length; i++) {
            for (int j = 0; j < visited[i].length; j++) {
                if (visited[i][j] == 1) {
                    return -1;
                }
            }
        }
        return level;
    }
}

#华为od#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:22
怎么这么多逆天求职者,救救我救救我救救我😭
flmz_Kk:哈哈哈哈哈哈,这么多求职者,肯定有那一两个逆天的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务