leetcode934 最短的桥

https://leetcode-cn.com/problems/shortest-bridge/
给定一个数组。数组中包含两个岛屿。求两个岛屿之间的最短距离。
采用找岛屿的方式(DFS),把其中的一个岛屿全部标记为2。并且用一个queue来存储上,此时采用BFS根据queue中的每一个节点逐步向外扩,直到遇到第一个数字1,也就找到了最短的距离。

class Solution { 
    public int shortestBridge(int[][] A) {
        int len1 = A.length;
        int len2 = A[0].length;
        Queue<int[]> q = new LinkedList<int[]>();
        boolean found = false;
        for(int i = 0; i<A.length && !found; i++){
            for(int j=0; j<A[0].length && !found; j++){
                if(A[i][j]==1){
                    dfs(A,i,j,q);
                    found = true;
                }
            }
        }

        int[][] dic = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
        int step = 0;
        while(!q.isEmpty()){
            int size = q.size();
            while(size>0){
                int x = q.peek()[0];
                int y = q.peek()[1];
                q.poll();
                for(int i = 0; i<4; i++){
                    int tx = x + dic[i][0];
                    int ty = y + dic[i][1];
                    if(tx<0 || ty<0 || tx>=len1 || ty>=len2 || A[tx][ty]==2){
                        continue;
                    }
                    if(A[tx][ty] == 1){
                        return step;
                    }
                    A[tx][ty] = 2;
                    q.add(new int[]{tx,ty});
                }
                size--;
            }
            step++;
        }
        return -1;
    }

    private void dfs(int[][] A, int i, int j, Queue<int[]> q){
        int len1 = A.length;
        int len2 = A[0].length;

        if(i<0 || j<0 || i>=len1 || j>=len2 || A[i][j]!=1){
            return;
        }
        A[i][j] = 2;
        q.add(new int[]{i,j});
        dfs(A,i-1,j,q);
        dfs(A,i+1,j,q);
        dfs(A,i,j-1,q);
        dfs(A,i,j+1,q);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值