码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 994. Rotting Oranges

时间:2020-03-01 12:42:36      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:link   offer   The   i++   range   min   nim   repr   code   

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

标签:link   offer   The   i++   range   min   nim   repr   code   

原文地址:https://www.cnblogs.com/xuanlu/p/12388795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!