|
| 1 | +from typing import List, Set, Tuple |
| 2 | +from collections import deque |
| 3 | + |
| 4 | +def best_bridge(grid: List[List]) -> int: |
| 5 | + visited = set() |
| 6 | + |
| 7 | + for r in range(len(grid)): |
| 8 | + for c in range(len(grid[0])): |
| 9 | + island = find_island(grid, r, c, visited) |
| 10 | + if len(island) > 0: |
| 11 | + break |
| 12 | + if len(island) > 0: |
| 13 | + first_island = island |
| 14 | + break |
| 15 | + |
| 16 | + if len(island) == 0: |
| 17 | + return "No island in sight" |
| 18 | + |
| 19 | + queue = deque([]) |
| 20 | + for pos in first_island: |
| 21 | + r, c = pos |
| 22 | + queue.append((r, c, 0)) |
| 23 | + |
| 24 | + newly_visited = set() |
| 25 | + |
| 26 | + while queue: |
| 27 | + curr_r, curr_c, distance = queue.popleft() |
| 28 | + curr_pos = curr_r, curr_c |
| 29 | + |
| 30 | + if grid[curr_r][curr_c] == "L" and curr_pos not in first_island: |
| 31 | + return distance - 1 |
| 32 | + |
| 33 | + deltas = deltas = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Possible directions to move in the grid |
| 34 | + for delta in deltas: |
| 35 | + delta_r, delta_c = delta |
| 36 | + neighbor_r = delta_r + curr_r |
| 37 | + neighbor_c = delta_c + curr_c |
| 38 | + neighbor_pos = neighbor_r, neighbor_c |
| 39 | + if inbounds(grid, neighbor_r, neighbor_c) and neighbor_pos not in newly_visited: |
| 40 | + newly_visited.add(neighbor_pos) |
| 41 | + queue.append((neighbor_r, neighbor_c, distance + 1)) |
| 42 | + return -1 |
| 43 | + |
| 44 | + |
| 45 | +def find_island(grid: List[List], r: int, c: int, visited: Set[Tuple]) -> bool: |
| 46 | + queue = deque([(r,c)]) |
| 47 | + |
| 48 | + while queue: |
| 49 | + curr_r, curr_c = queue.popleft() |
| 50 | + curr_pos = curr_r, curr_c |
| 51 | + |
| 52 | + if grid[curr_r][curr_c] == "W" or curr_pos in visited: |
| 53 | + continue |
| 54 | + |
| 55 | + visited.add(curr_pos) |
| 56 | + deltas = deltas = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Possible directions to move in the grid |
| 57 | + for delta in deltas: |
| 58 | + delta_r, delta_c = delta |
| 59 | + neighbor_r = delta_r + r |
| 60 | + neighbor_c = delta_c + c |
| 61 | + if inbounds(grid, neighbor_r, neighbor_c): |
| 62 | + queue.append((neighbor_r, neighbor_c)) |
| 63 | + |
| 64 | + return visited |
| 65 | + |
| 66 | +def inbounds(grid: List[List], r: int, c: int) -> bool: |
| 67 | + row_inbounds = 0 <= r < len(grid) |
| 68 | + col_inbounds = 0 <= c < len(grid[0]) |
| 69 | + |
| 70 | + return row_inbounds and col_inbounds |
| 71 | + |
0 commit comments