Skip to main content

Command Palette

Search for a command to run...

oranges rotten

Published
1 min readView as Markdown
class Solution {

 public static class Pair {
        int row ,col;
        Pair(int row, int col) {
            this.row = row;
            this.col = col;
        }
    }

    public int orangesRotting(int[][] grid) {

        Queue<Pair> st = new LinkedList<>();

        int fresh=0;
        for(int i=0;i<grid.length;i++)
        {
            for(int j=0;j<grid[0].length;j++)
            {
                if(grid[i][j]==2)
                {
                    st.add(new Pair(i,j));
                }
                else if(grid[i][j]==1)
                {
                    fresh++;
                }
            }
        }

        if(fresh==0)
        {
            return 0;
        }


        int dir[][]= {{0,1},{0,-1},{1,0},{-1,0}};
         int min=0;
         while(!st.isEmpty())
         {
            int size= st.size();
            min++;
            while(size>0)
            {
                size--;
                Pair s= st.poll();
                for(int k=0;k<4;k++)
                {
                    int x= s.row + dir[k][0];
                    int y= s.col + dir[k][1];           
                    if(x>=0 && y>=0 && x<grid.length && y<grid[0].length && grid[x][y]==1)
                    {
                        grid[x][y]=2;
                       st.add(new Pair(x, y));
                       fresh--; 
                    }
                }
            }
         }

         if(fresh==0)
         {
            return min-1;
         }
         else
         {
            return -1;
         }













    }
}

More from this blog

Amit singh's blog

235 posts

oranges rotten