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;
        }
    }
  • 相关阅读:
    #翻译# 深入JavaScript的Unicode难题(上)
    深入 JavaScript(6)
    Angular service, 服务
    [译] 什么是移动友好的
    [译] 新手和老手都将受益的JavaScript小技巧
    Create XHR
    计算新浪Weibo消息长度
    SpringMVCDemo中,遇到的问题(四) 之分页功能
    为什么要用where 1=1?
    SpringMVCDemo中,遇到的问题(二)之mybatis中的mapper映射
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12388795.html
Copyright © 2011-2022 走看看