<p>You are given an <code>n x n</code> binary matrix <code>grid</code> where <code>1</code> represents land and <code>0</code> represents water.</p>

<p>An <strong>island</strong> is a 4-directionally connected group of <code>1</code>&#39;s not connected to any other <code>1</code>&#39;s. There are <strong>exactly two islands</strong> in <code>grid</code>.</p>

<p>You may change <code>0</code>&#39;s to <code>1</code>&#39;s to connect the two islands to form <strong>one island</strong>.</p>

<p>Return <em>the smallest number of </em><code>0</code><em>&#39;s you must flip to connect the two islands</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [[0,1],[1,0]]
<strong>Output:</strong> 1
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[0,1,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> grid = [[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]]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length == grid[i].length</code></li>
	<li><code>2 &lt;= n &lt;= 100</code></li>
	<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
	<li>There are exactly two islands in <code>grid</code>.</li>
</ul>

from collections import deque
class Solution:
    def shortestBridge(self, grid: List[List[int]]) -> int:
        R = len(grid)
        C = len(grid[0])
        islands = [[0 for _ in range(C)] for _ in range(R)]
        dirs = [(0,1), (0,-1), (1,0), (-1,0)]
        outlines = []

        def bfs(i,j, islandNumber, isPrecompute, visited):          
            q = deque([(i,j, 0)])
            shortestPath = float('inf')
            while q:
                (i, j, dist) = q.popleft()
                if (0 <= i < R and 0 <= j < C) and not visited[i][j]:
                    visited[i][j] = True
                    if isPrecompute:
                        if grid[i][j] != 0:
                            islands[i][j] = islandNumber
                            for (iN, jN) in dirs:
                                if islandNumber == 2 and 0 <= i+iN < R and 0 <= j+jN < C and grid[i+iN][j+jN] == 0:
                                    outlines.append((i,j))
                                q.append((i+iN, j+jN, dist+1))
                    else:
                        # finding shortest path
                        for (iN, jN) in dirs:
                            if 0 <= i+iN < R and 0 <= j+jN < C:
                                if islands[i+iN][j+jN] == 3:
                                    return dist
                                elif islands[i+iN][j+jN] == 0:
                                    # only go to water to save time
                                    q.append((i+iN, j+jN, dist+1))
                        
            return shortestPath


        # precompute
        islandNumber = 2
        visited = [[False for _ in range(C)] for _ in range(R)]
        for i in range(R):
            for j in range(C):
                if grid[i][j] == 1 and not visited[i][j]:
                    bfs(i,j, islandNumber, True, visited)
                    islandNumber += 1
        
        
        shortestPath = float('inf')
        for i,j in outlines:
            visited = [[False for _ in range(C)] for _ in range(R)]
            shortestPath = min(shortestPath, bfs(i,j, 2, False, visited))
        
        return shortestPath



            

17300