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#
全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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