Leetcode_934_最短的桥_广度优先搜索

难度不高,但是代码量还是比较多的,锻炼基本功挺不错的

class Solution {
    private static final int[][] directions = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

    public int shortestBridge(int[][] grid) {
        // 找到一个为1的点
        int m = grid.length;
        // 数据不可能出现grid[0]=null,这里不会空指针
        int n = grid[0].length;
        int[] point = new int[2];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    point[0] = i;
                    point[1] = j;
                }
            }
        }

        // 找到这个1的点所在的岛,并将他们全部标记为-1
        Deque<int[]> points = new ArrayDeque<>();
        // 临时队列
        List<int[]> temp = new ArrayList<>();
        temp.add(point);

        while(!temp.isEmpty()) {
            int[] nowPoint = temp.remove(temp.size() - 1);
            points.addLast(nowPoint);
            grid[nowPoint[0]][nowPoint[1]] = -1;
            for (int[] direction : directions) {
                int nextX = nowPoint[0] + direction[0];
                int nextY = nowPoint[1] + direction[1];
                if(judgeNode(nextX, nextY, m, n) && grid[nextX][nextY] == 1) {
                    int[] nextPoint = new  int[2];
                    nextPoint[0] = nextX;
                    nextPoint[1] = nextY;
                    points.addLast(nextPoint);
                    temp.add(nextPoint);
                }
            }
        }

        int step = 0;

        while(!points.isEmpty()) {
            int size = points.size();
            for (int i = 0; i < size; i++) {
                int[] nowPoint = points.removeFirst();
                for (int[] direction : directions) {
                    int nextX = nowPoint[0] + direction[0];
                    int nextY = nowPoint[1] + direction[1];
                    if(judgeNode(nextX, nextY, m, n)) {
                        if(grid[nextX][nextY] == 1) {
                            return step;
                        }
                        if(grid[nextX][nextY] == -1) {
                            continue;
                        }
                        grid[nextX][nextY] = -1;
                        int[] nextPoint = new  int[2];
                        nextPoint[0] = nextX;
                        nextPoint[1] = nextY;
                        points.addLast(nextPoint);
                    }
                }
            }
            step++;
        }
        return step;
    }
    
    boolean judgeNode(int nextX, int nextY, int m, int n) {
        return nextX >= 0 && nextX < m && nextY >= 0 && nextY < n;
    }
}

你可能感兴趣的:(bfs,daily_algorithm,leetcode,宽度优先,算法)