Rotting Oranges

/*
 本算法答案由上岸科技提供。
 上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
 我们采用小班化线上,线下教学让学生更快,更好的学习到想要的知识。
 团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
 我们坚信对于求职者算法并不是全部,合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
 正如我们的信仰:我们教的是如何上岸而不仅是算法。
 更多信息请关注官网:https://www.shanganonline.com/
*/
class Solution {
    private static final int[] xBias = {0, 0, 1, -1};
    private static final int[] yBias = {1, -1, 0, 0};
    
    public int orangesRotting(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return -1;
        }
        int m = grid.length;
        int n = grid[0].length;
        Queue<Integer> queue = new ArrayDeque<>();
        int fresh = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    fresh++;
                } else if (grid[i][j] == 2) {
                    queue.offer(i * n + j);
                }
            }
        }
        
        int minute = 0;
        while (!queue.isEmpty() && fresh != 0) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int index = queue.poll();
                int x = index / n;
                int y = index % n;
                for (int j = 0; j < xBias.length; j++) {
                    int newX = x + xBias[j];
                    int newY = y + yBias[j];
                    if (notValid(grid, newX, newY)) {
                        continue;
                    }
                    fresh--;
                    queue.offer(newX * n + newY);
                    grid[newX][newY] = 2;
                }
            }
            minute++;
        }
        return fresh == 0 ? minute : -1;
    }
    
    private boolean notValid(int[][] grid, int x, int y) {
        return x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] != 1;
    }
}

Last updated

Was this helpful?