Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int rottonCount = 0;
- int totalCount = 0;
- int m,n;
- public int orangesRotting(int[][] grid) {
- m = grid.length;
- n = grid[0].length;
- Queue<Point> kyu = new LinkedList<>();
- for(int i=0;i<m;++i){
- for(int j=0;j<n;++j){
- if(grid[i][j] > 0){
- totalCount++;
- if(grid[i][j] == 2){
- rottonCount++;
- kyu.add(new Point(i, j));
- }
- }
- }
- }
- int level = 0;
- // null is delimeter
- kyu.add(null);
- int freshCount = totalCount - rottonCount;
- while(!kyu.isEmpty()){
- Point p = kyu.poll();
- if(Objects.isNull(p)){
- level++;
- if(!kyu.isEmpty()){
- kyu.add(null);
- }
- } else {
- for(Point t : getNearbyFresh(p, grid)){
- freshCount--;
- kyu.add(t);
- }
- }
- }
- if(freshCount == 0)
- return level-1;
- return -1;
- }
- public List<Point> getNearbyFresh(Point p, int[][] grid){
- int[][] steps = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
- List<Point> list = new LinkedList<>();
- for(int[] step : steps){
- int x = p.x + step[0];
- int y = p.y + step[1];
- if(x >= 0 && x < m && y>=0&&y < n && grid[x][y]==1){
- grid[x][y] = 2;
- list.add(new Point(x, y));
- }
- }
- return list;
- }
- class Point{
- int x,y;
- Point(int x, int y){
- this.x = x;this.y = y;
- }
- public String toString(){
- return (String.format(" [%s,%s]", x, y ));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement