Advertisement
psO1

rotting oranges

Jan 27th, 2025
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. class Solution {
  2.     int freshCount = 0;
  3.     Queue<Pair> queue = new LinkedList<>();
  4.  
  5.     public int orangesRotting(int[][] grid) {
  6.  
  7.         for (int i = 0; i < grid.length; i++) {
  8.             for (int j = 0; j < grid[i].length; j++) {
  9.                 if (grid[i][j] == 2) {
  10.                     queue.offer(new Pair(i,j)); // Rotten oranges
  11.                 }
  12.                 if (grid[i][j] == 1) freshCount++;
  13.             }
  14.         }
  15.         int count = 0;
  16.         while (!queue.isEmpty()) {
  17.             rotOranges(grid);
  18.             count++;
  19.         }
  20.         if (freshCount > 0) return -1;
  21.         return count == 0 ? count : count-1;
  22.     }
  23.  
  24.     private void rotOranges(int[][] grid) {
  25.        
  26.         int size = queue.size();
  27.         for (int i = 0; i < size; i++) {
  28.             Pair indexes = queue.poll();
  29.  
  30.             List<Pair> nextRotten = getAlongSide(grid, indexes.i, indexes.j);
  31.             for(Pair p: nextRotten) {
  32.            
  33.                 grid[p.i][p.j] = 2;
  34.                 freshCount--;
  35.                 queue.offer(p);
  36.        
  37.             }
  38.         }
  39.     }
  40.  
  41.     public List<Pair> getAlongSide(int[][] grid, int i, int j) {
  42.         List<Pair> result = new ArrayList<>();
  43.         if (isSafeDown(grid, i, j)) result.add(new Pair(i+1, j));
  44.         if (isSafeUp(grid, i, j)) result.add(new Pair(i-1, j));
  45.         if (isSafeLeft(j, grid[i])) result.add(new Pair(i, j+1));
  46.         if (isSafeRight(j, grid[i])) result.add(new Pair(i, j-1));
  47.         return result;
  48.     }
  49.  
  50.     private static boolean isSafeUp(int[][] grid, int i, int j) {
  51.         return i - 1 >= 0 && grid[i - 1][j] == 1;
  52.     }
  53.  
  54.     private static boolean isSafeRight(int j, int[] grid) {
  55.         return j - 1 >= 0 && grid[j - 1] == 1;
  56.     }
  57.  
  58.     private static boolean isSafeDown(int[][] grid, int i, int j) {
  59.         return i + 1 < grid.length && grid[i + 1][j] == 1;
  60.     }
  61.  
  62.     private static boolean isSafeLeft(int j, int[] grid) {
  63.         return j + 1 < grid.length && grid[j + 1] == 1;
  64.     }
  65. }
  66.  
  67. class Pair {
  68.     int i, j;
  69.     public Pair(int i, int j) {
  70.         this.i = i;
  71.         this.j = j;
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement