|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Queue; |
| 5 | + |
| 6 | +/** |
| 7 | + * 994. Rotting Oranges |
| 8 | + * |
| 9 | + * In a given grid, each cell can have one of three values: |
| 10 | + * |
| 11 | + * the value 0 representing an empty cell; |
| 12 | + * the value 1 representing a fresh orange; |
| 13 | + * the value 2 representing a rotten orange. |
| 14 | + * |
| 15 | + * Every minute, any fresh orange that is adjacent (4-directionally) to a |
| 16 | + * rotten orange becomes rotten. |
| 17 | + * |
| 18 | + * Return the minimum number of minutes that must elapse until no cell has a fresh orange. |
| 19 | + * If this is impossible, return -1 instead. |
| 20 | + * |
| 21 | + * Example 1: |
| 22 | + * Input: [[2,1,1],[1,1,0],[0,1,1]] |
| 23 | + * Output: 4 |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * Input: [[2,1,1],[0,1,1],[1,0,1]] |
| 27 | + * Output: -1 |
| 28 | + * Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. |
| 29 | + * |
| 30 | + * Example 3: |
| 31 | + * Input: [[0,2]] |
| 32 | + * Output: 0 |
| 33 | + * Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. |
| 34 | + * |
| 35 | + * Note: |
| 36 | + * |
| 37 | + * 1 <= grid.length <= 10 |
| 38 | + * 1 <= grid[0].length <= 10 |
| 39 | + * grid[i][j] is only 0, 1, or 2. |
| 40 | + */ |
| 41 | +public class _994 { |
| 42 | + public static class Solution1 { |
| 43 | + int[] directions = new int[] {0, 1, 0, -1, 0}; |
| 44 | + |
| 45 | + public int orangesRotting(int[][] grid) { |
| 46 | + Queue<int[]> rottens = new LinkedList<>(); |
| 47 | + for (int i = 0; i < grid.length; i++) { |
| 48 | + for (int j = 0; j < grid[0].length; j++) { |
| 49 | + if (grid[i][j] == 2) { |
| 50 | + rottens.add(new int[] {i, j}); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + int times = 0; |
| 55 | + while (!rottens.isEmpty()) { |
| 56 | + int size = rottens.size(); |
| 57 | + boolean counted = false; |
| 58 | + for (int k = 0; k < size; k++) { |
| 59 | + int[] rotten = rottens.poll(); |
| 60 | + for (int i = 0; i < 4; i++) { |
| 61 | + int x = rotten[0] + directions[i]; |
| 62 | + int y = rotten[1] + directions[i + 1]; |
| 63 | + if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == 1) { |
| 64 | + grid[x][y] = 2; |
| 65 | + if (!counted) { |
| 66 | + times++; |
| 67 | + } |
| 68 | + counted = true; |
| 69 | + rottens.add(new int[] {x, y}); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + for (int i = 0; i < grid.length; i++) { |
| 75 | + for (int j = 0; j < grid[0].length; j++) { |
| 76 | + if (grid[i][j] == 1) { |
| 77 | + return -1; |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + return times; |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments