Java教程

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);
                   }
                }
            }
        }
    }
}

 

这篇关于286. Walls and Gates的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!