zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    linux 命令——19 find (转)
    linux 命令——18 locate (转)
    linux 命令——17 whereis(转)
    linux 命令——16 which(转)
    linux 命令——15 tail (转)
    linux 命令——14 head (转)
    Java for LeetCode 038 Count and Say
    Java for LeetCode 037 Sudoku Solver
    Java for LeetCode 036 Valid Sudoku
    Java for LeetCode 035 Search Insert Position
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12388795.html
Copyright © 2011-2022 走看看