Advertisement
veryinnocentboy

rotting-oranges.java

Jun 2nd, 2021
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. class Solution {
  2.     int rottonCount = 0;
  3.     int totalCount = 0;
  4.     int m,n;
  5.     public int orangesRotting(int[][] grid) {
  6.             m = grid.length;
  7.         n = grid[0].length;
  8.         Queue<Point> kyu = new LinkedList<>();
  9.         for(int i=0;i<m;++i){
  10.             for(int j=0;j<n;++j){
  11.                 if(grid[i][j] > 0){
  12.                     totalCount++;
  13.                     if(grid[i][j] == 2){
  14.                         rottonCount++;
  15.                         kyu.add(new Point(i, j));
  16.                     }
  17.                 }
  18.             }
  19.         }
  20.         int level = 0;
  21.         // null is delimeter
  22.         kyu.add(null);
  23.         int freshCount = totalCount - rottonCount;
  24.        
  25.        
  26.         while(!kyu.isEmpty()){
  27.             Point p = kyu.poll();
  28.             if(Objects.isNull(p)){
  29.                 level++;
  30.                 if(!kyu.isEmpty()){
  31.                     kyu.add(null);
  32.                 }
  33.             } else {
  34.                 for(Point t  : getNearbyFresh(p, grid)){
  35.                     freshCount--;
  36.                     kyu.add(t);
  37.                 }    
  38.             }
  39.         }
  40.         if(freshCount == 0)
  41.             return level-1;
  42.         return -1;
  43.     }
  44.     public List<Point> getNearbyFresh(Point p, int[][] grid){
  45.         int[][] steps = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
  46.         List<Point> list = new LinkedList<>();
  47.         for(int[] step : steps){
  48.             int x = p.x + step[0];
  49.             int y = p.y + step[1];
  50.             if(x >= 0 && x < m && y>=0&&y < n && grid[x][y]==1){
  51.                 grid[x][y] = 2;
  52.                 list.add(new Point(x, y));
  53.             }
  54.         }
  55.         return list;
  56.     }
  57.    
  58.     class Point{
  59.         int x,y;
  60.         Point(int x, int y){
  61.             this.x = x;this.y = y;
  62.         }
  63.         public String toString(){
  64.             return (String.format(" [%s,%s]", x, y ));
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement