Shortest Bridge

BFS

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.)

Thought Process

  • We care about levels here

  • We use DFS to find the first isalnd and change the connecting components to -1. Then we used BFS to find the other island

Solution

Time Complexity

  • Time: O(n^2) because it depends on the DFS. If we have all 1's then the time will be O(n^2)

  • Space: O(n^2) for the recursion stack of DFS

Last updated

Was this helpful?