934 Shortest Bridge
934. Shortest Bridge
1. Question
In a given 2D binary arrayA, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change0s to1s so as to connect the two islands together to form 1 island.
Return the smallest number of0s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: [[0,1],[1,0]]
Output: 1Example 2:
Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2Example 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: 1Note:
1 <= A.length = A[0].length <= 100A[i][j] == 0orA[i][j] == 1
2. Implementation
(1) DFS + BFS
思路:
先用DFS找到一个island
然后用BFS将找到的island expand,直至到达另一个island
3. Time & Space Complexity
时间复杂度O(mn), 空间复杂度O(mn)
Last updated
Was this helpful?