其他分享
首页 > 其他分享> > 286. Walls and Gates

286. Walls and Gates

作者:互联网

The solution of this issue is as same as 542. 01 Matrix

class Solution {
    int m, n;
    private int[][] dirs ={{-1,0},{1,0},{0,-1},{0,1}};
    public void wallsAndGates(int[][] rooms) {
        if(rooms==null || rooms.length==0)
            return;
        m = rooms.length;
        n = rooms[0].length;
        
        Queue<int[]> queue = new LinkedList<>();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(rooms[i][j]==0){
                    queue.offer(new int[]{i,j});
                }
            }
        }
        int count = 0;
        while(!queue.isEmpty()){
            count++;
            int size = queue.size();
            for(int i=0;i<size;i++){
                int[] cell = queue.poll();
                for(int[] dir: dirs){
                    int x = cell[0]+dir[0];
                    int y = cell[1]+dir[1];
                    if(x<0||x>=m||y<0||y>=n||rooms[x][y]==-1||rooms[x][y]==0)
                        continue;
                   if(rooms[x][y]==Integer.MAX_VALUE){
                        queue.offer(new int[]{x,y});
                        rooms[x][y]=Math.min(rooms[x][y],count);
                   }
                }
            }
        }
    }
}

 

标签:Gates,Matrix,int,length,queue,Walls,rooms,new,286
来源: https://www.cnblogs.com/feiflytech/p/15983378.html