Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f11766e

Browse files
feat: add best bridge v2
1 parent 65effb4 commit f11766e

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

‎graphs/best_bridge/best_bridge_v2.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from typing import List, Set
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+
43+
return -1
44+
45+
46+
def find_island(grid: List[List], r: int, c: int, visited: Set) -> Set:
47+
stack = [(r, c)]
48+
49+
50+
while stack:
51+
r, c = stack.pop()
52+
pos = r, c
53+
54+
if grid[r][c] == "W" or pos in visited:
55+
continue
56+
57+
visited.add(pos)
58+
deltas = deltas = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Possible directions to move in the grid
59+
for delta in deltas:
60+
delta_r, delta_c = delta
61+
neighbor_r = delta_r + r
62+
neighbor_c = delta_c + c
63+
if inbounds(grid, neighbor_r, neighbor_c):
64+
stack.append((neighbor_r, neighbor_c))
65+
66+
return visited
67+
68+
def inbounds(grid: List[List], r: int, c: int) -> bool:
69+
row_inbounds = 0 <= r < len(grid)
70+
col_inbounds = 0 <= c < len(grid[0])
71+
72+
return row_inbounds and col_inbounds
73+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /