[LeetCode] 934. Shortest Bridge

Problem

In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

Return the smallest number of 0s that must be flipped. (It is guaranteed that the answer is at least 1.)

Example 1:

Input: [[0,1],[1,0]]
Output: 1
Example 2:

Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Example 3:

Input: [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1

Note:

1 <= A.length = A[0].length <= 100
Ai == 0 or Ai == 1

Solution

class Solution {
    public int shortestBridge(int[][] A) {
        //find the first island, using dfs
        int m = A.length, n = A[0].length;
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>(); //for bfs
        int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
        
        boolean found = false;
        for (int i = 0; i < m; i++) {
            if (found) break;
            for (int j = 0; j < n; j++) {
                if (A[i][j] == 1) {
                    found = true;
                    dfs(A, i, j, visited, dirs, queue);
                    break;
                }
            }
        }
        
        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                for (int[] dir: dirs) {
                    int x = cur[0]+dir[0], y = cur[1]+dir[1];
                    if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
                    if (A[x][y] == 1) return count;
                    queue.offer(new int[]{x, y});
                    visited[x][y] = true;
                }
            }
            count++;
        }
        return -1;
    }
    
    private void dfs(int[][] A, int i, int j, boolean[][] visited, int[][] dirs, Queue<int[]> queue) {
        int m = A.length, n = A[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n || A[i][j] == 0 || visited[i][j]) return;
        queue.offer(new int[]{i, j});
        visited[i][j] = true;
        for (int[] dir: dirs) {
            dfs(A, i+dir[0], j+dir[1], visited, dirs, queue);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值