[LC] 994. Rotting Oranges

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 994. Rotting Oranges相关的知识,希望对你有一定的参考价值。

In a given grid, each cell can have one of three values:

  • the value 0 representing an empty cell;
  • the value 1 representing a fresh orange;
  • the value 2 representing a rotten orange.

Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange.  If this is impossible, return -1 instead.

 

class Solution {
    public int orangesRotting(int[][] grid) {
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int numOrange = 0;
        int row = grid.length;
        int col = grid[0].length;
        Queue<Cell> queue = new LinkedList<>();

        int res = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 2) {
                    queue.offer(new Cell(i, j, grid[i][j]));
                } else if (grid[i][j] == 1) {
                    numOrange += 1;
                }  
            }
        }
        
        // no fresh orange
        if (numOrange == 0) {
            return 0;
        }
        
        int[] directX = {-1, 0, 0, 1};
        int[] directY = {0, -1, 1, 0};
        while(!queue.isEmpty()) {
            int size = queue.size();
            res += 1;
            for (int i = 0; i < size; i++) {
                Cell cur = queue.poll();
                for (int k = 0; k < 4; k++) {
                    int nextX = cur.x + directX[k];
                    int nextY = cur.y + directY[k];
                    if (nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length && grid[nextX][nextY] == 1) {
                        queue.offer(new Cell(nextX, nextY, grid[nextX][nextY]));
                        grid[nextX][nextY] = 2;
                        numOrange -= 1;
                        if (numOrange == 0) {
                            return res;
                        }
                    }
                }
            }
        }       
        return -1;
    }
}

class Cell {
    int x;
    int y;
    int value;
    public Cell(int x, int y, int value) {
        this.x = x;
        this.y = y;
        this.value = value;
    }
}

 

以上是关于[LC] 994. Rotting Oranges的主要内容,如果未能解决你的问题,请参考以下文章

994. Rotting Oranges[Medium]

Leetcode_easy994. Rotting Oranges

[LeetCode] 994. Rotting Oranges

Leetcode 994. Rotting Oranges

Leetcode-994 Rotting Oranges(腐烂的橘子)

leetcode 994. 腐烂的橘子(Rotting Oranges)