LeetCode 0934. Shortest Bridge Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0934. Shortest Bridge

Description

You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.

You may change 0's to 1's to connect the two islands to form one island.

Return the smallest number of 0's you must flip to connect the two islands.

 

Example 1:

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

Example 2:

Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 3:

Input: 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]]
Output: 1

 

Constraints:

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is either 0 or 1.
  • There are exactly two islands in grid.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def shortestBridge(self, grid: List[List[int]]) -> int: def dfs(i, j): q.append((i, j)) grid[i][j] = 2 for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < n and 0 <= y < n and grid[x][y] == 1: dfs(x, y) n = len(grid) dirs = (-1, 0, 1, 0, -1) q = deque() i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j]) dfs(i, j) ans = 0 while 1: for _ in range(len(q)): i, j = q.popleft() for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < n and 0 <= y < n: if grid[x][y] == 1: return ans if grid[x][y] == 0: grid[x][y] = 2 q.append((x, y)) ans += 1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !