934. 最短的桥

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-bridge
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


将一个岛的值设置为-1,之后让1的到一圈一圈的找,直到找到-1.

    public int shortestBridge(int[][] grid) {

        Queue<int[]> queue = new LinkedList<>();
        boolean flag = false;
        for(int i=0;i<grid.length;i++) {
            for(int j=0;j<grid[0].length;j++) {
                if(grid[i][j] == 1) {
                    if(!flag) {
                        dfs(grid,i,j);
                    }else {
                        queue.add(new int[]{i,j});
                    }
                    flag = true;
                }
            }

        }
        int count = 2;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i=0;i<size;i++) {
                int[] pos = queue.poll();
                int[] dx = new int[]{0,0,1,-1};
                int[] dy = new int[]{1,-1,0,0};

                for(int t=0;t<4;t++) {
                    int newX = pos[0] + dx[t];
                    int newY = pos[1] + dy[t];
                    if(newX <0 || newX>=grid.length || newY <0 || newY>=grid[0].length) {
                        continue;
                    }
                    if(grid[newX][newY] !=0) {
                        if(grid[newX][newY] == -1) {
                            return count-2;
                        }
                        continue;
                    }
                    grid[newX][newY] = count;
                    queue.add(new int[]{newX,newY});
                }
            }
            count++;
        }
        return count;

    }

    public void dfs(int[][] grid, int i,int j) {
        // 将1的位置变成-1,所以不是1的就停止了。
        if(i<0|| i>= grid.length || j<0 || j>=grid[0].length || grid[i][j] != 1 ) {
            return;
        }

        grid[i][j] = -1;
        // queue.add(new int[]{i,j});
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
        dfs(grid,i,j+1); 
        dfs(grid,i,j-1);
    }

posted @ 2022-03-01 15:36  一颗青菜  阅读(11)  评论(0)    收藏  举报