A little different JAVA solution than DFS/BFS but similar idea


  • 0
    C
        public void wallsAndGates(int[][] rooms)
        {
            int k = 0;
            int count;
            
            do
            {
                count = 0;
                
                for(int i = 0; i < rooms.length; i++)
                {
                    for(int j = 0; j < rooms[0].length; j++)
                    {
                        if(rooms[i][j] == 2147483647)
                        {
                            if(i + 1 < rooms.length && rooms[i + 1][j] == k)
                            {
                                rooms[i][j] = k + 1;
                                count++;
                            }
                            
                            else if(i - 1 >= 0 && rooms[i - 1][j] == k)
                            {
                                rooms[i][j] = k + 1;
                                count++;
                            }
                            
                            else if(j + 1 < rooms[0].length && rooms[i][j + 1] == k)
                            {
                                rooms[i][j] = k + 1;
                                count++;
                            }
                            
                            else if(j - 1 >= 0 && rooms[i][j - 1] == k)
                            {
                                rooms[i][j] = k + 1;
                                count++;
                            }
                        }
                    }
                }
                
                k++;
                
    
            }while(count > 0);
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.