Shortest Bridge
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:
分析
dfs+bfs
先dfs把第一个岛都标记visited并且塞进q
再bfs一层层扩展,记得遇到1直接返回。还有入栈时候标记visited
Last updated
Was this helpful?