标签:link offer The i++ range min nim repr code
In a given grid, each cell can have one of three values:
0
representing an empty cell;1
representing a fresh orange;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; } }
标签:link offer The i++ range min nim repr code
原文地址:https://www.cnblogs.com/xuanlu/p/12388795.html