[Leetcode] 286. Walls and Gates

这一题其实就是一条很基础的BFS寻图题。就是由一个起点出发然后遍历周边可以走的点。DFS其实也可以做,但是BFS做起来会有更好的PERFORMANCE。就是先收集起点,然后往外扩散有效的点(也就是没走过的,值为INF的点)。

    public static int[][] DIR = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public void wallsAndGates(int[][] rooms) {
        Queue<int[]> bfsQ = new LinkedList<int[]>();
        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[0].length; j++) {
                if (rooms[i][j] == 0) {
                    bfsQ.add(new int[]{i, j});
                }
            }
        }
        
        while (!bfsQ.isEmpty()) {
            int[] curPt = bfsQ.poll();
            int x = curPt[0], y = curPt[1];
            for (int i = 0; i < Solution.DIR.length; i++) {
                int nextX = x + Solution.DIR[i][0], nextY = y + Solution.DIR[i][1];
                if (nextX >= rooms.length || nextX < 0 || nextY >= rooms[0].length || nextY < 0 || rooms[nextX][nextY] != Integer.MAX_VALUE) {
                    continue;
                }
                
                rooms[nextX][nextY] = rooms[x][y] + 1;
                bfsQ.add(new int[]{nextX, nextY});
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/chaochen1407/article/details/82585023