Clear Java BFS Solution


  • 0
    Q
    public class Solution {
    public void wallsAndGates(int[][] rooms) {
    
        if(rooms.length==0)
            return;
        Queue <int[]> queue = new LinkedList<int[]>();
        int[] dx= {0,1,-1,0};
        int[] dy= {1,0,0,-1};
        
        for(int i=0;i<rooms.length;i++){
            for(int j=0;j<rooms[i].length;j++){
                if(rooms[i][j]==0)
                    queue.offer(new int[]{i,j});
            }
        }
        
        while(!queue.isEmpty()){
            int[] door=queue.poll();
            int row= door[0];
            int col=door[1];
            
            for(int d=0;d<dx.length;d++){
                if(row+dy[d]>=0&&row+dy[d]<rooms.length&&col+dx[d]>=0&&col+dx[d]<rooms[0].length&&rooms[row+dy[d]][col+dx[d]]==Integer.MAX_VALUE){
                    rooms[row+dy[d]][col+dx[d]]=rooms[row][col]+1;
                    queue.offer(new int[]{row+dy[d],col+dx[d]});
                }
            }
        }
    }
    

    }


Log in to reply
 

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