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 65effb4

Browse files
Merge pull request #348 from MoigeMatino/document-best-bridge
doc: document best bridge
2 parents 4c7280c + 0929ca2 commit 65effb4

File tree

1 file changed

+85
-35
lines changed

1 file changed

+85
-35
lines changed

‎graphs/best_bridge/best_bridge.py

Lines changed: 85 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,120 @@
11
from typing import List, Set
22
from collections import deque
33

4-
def best_bridge(grid:List[List]) -> int:
5-
visited = set()
4+
def best_bridge(grid: List[List]) -> int:
5+
"""
6+
Finds the length of the shortest bridge connecting two islands in a grid.
67
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:
8+
Args:
9+
grid: A 2D list representing the grid, where 'L' represents land and 'W' represents water.
10+
11+
Returns:
12+
The length of the shortest bridge, or -1 if no bridge can be found.
13+
"""
14+
15+
visited = set() # Set to keep track of visited cells
16+
17+
for r in range(len(grid)): # Iterate through each row
18+
for c in range(len(grid[0])): # Iterate through each column
19+
island = find_island(grid, r, c, visited) # Find an island starting from (r, c)
20+
if len(island) > 0: # If an island is found
1121
break
12-
if len(island) > 0:
13-
first_island = island
14-
print(first_island)
22+
if len(island) > 0: # If an island is found in this row
23+
first_island = island # Store the first found island
1524
break
16-
if len(island) == 0:
17-
return "No island in sight"
18-
19-
queue = deque([])
20-
for pos in first_island:
25+
if len(island) == 0:# If no island is found
26+
return "No island in sight"# Indicate no island
27+
28+
queue = deque([])# Queue for BFS
29+
for pos in first_island:# Initialize the queue with the first island's positions
2130
r, c = pos
22-
queue.append((r, c, 0))
31+
queue.append((r, c, 0)) # Add positions with distance 0 to the queue
32+
33+
newly_visited = set() # Set to keep track of newly visited cells in BFS
2334

24-
newly_visited = set()
25-
2635
while queue:
27-
r, c, distance = queue.popleft()
36+
r, c, distance = queue.popleft()# Get the next position and distance from the queue
2837
pos = r, c
29-
30-
if grid[r][c] == "L" and pos not in first_island:
31-
return distance - 1
32-
33-
deltas = [(1,0), (-1,0), (0,1), (0, -1)]
38+
39+
if grid[r][c] == "L" and pos not in first_island:# If found the second island
40+
return distance - 1# Return the distance minus 1 (since we started at 0)
41+
42+
deltas = [(1,0), (-1,0), (0,1), (0, -1)]# Possible directions to move in the grid
3443
for delta in deltas:
3544
delta_r, delta_c = delta
3645
neighbor_r = delta_r + r
3746
neighbor_c = delta_c + c
3847
neighbor_pos = neighbor_r, neighbor_c
3948
if inbounds(grid, neighbor_r, neighbor_c) and neighbor_pos not in newly_visited:
4049
newly_visited.add(neighbor_pos)
41-
queue.append((neighbor_r, neighbor_c, distance+1))
50+
queue.append((neighbor_r, neighbor_c, distance+1))
4251

43-
return -1
52+
return -1# No bridge found
4453

54+
def find_island(grid: List[List], r: int, c: int, visited: Set) -> Set:
55+
"""
56+
Finds an island starting from a given position.
57+
58+
Args:
59+
grid: The grid representing the land and water.
60+
r: The row of the starting position.
61+
c: The column of the starting position.
62+
visited: A set to keep track of visited cells.
63+
64+
Returns:
65+
A set of positions representing the island.
66+
"""
4567

46-
def find_island(grid:List[List], r:int, c:int, visited:Set) -> Set:
4768
if not inbounds(grid, r, c):
48-
return visited
69+
return visited# Return visited if the cell is out of bounds
4970

5071
if grid[r][c] == "W":
51-
return visited
72+
return visited# Return visited if the cell is water
5273

5374
pos = r, c
5475
if pos in visited:
55-
return visited
76+
return visited# Return visited if the cell has already been visited
5677

57-
visited.add(pos)
78+
visited.add(pos)# Mark the cell as visited
5879

59-
find_island(grid, r+1, c, visited)
60-
find_island(grid, r-1, c, visited)
61-
find_island(grid, r, c+1, visited)
62-
find_island(grid, r, c-1, visited)
80+
# Recursively visit neighboring cells
81+
find_island(grid, r + 1, c, visited)
82+
find_island(grid, r - 1, c, visited)
83+
find_island(grid, r, c + 1, visited)
84+
find_island(grid, r, c - 1, visited)
6385

6486
return visited
6587

66-
def inbounds(grid:List[List], r:int, c:int) -> bool:
88+
def inbounds(grid: List[List], r: int, c: int) -> bool:
89+
"""
90+
Checks if a given position is within the grid boundaries.
91+
92+
Args:
93+
grid: The grid.
94+
r: The row.
95+
c: The column.
96+
97+
Returns:
98+
True if the position is in bounds, False otherwise.
99+
"""
100+
67101
row_inbounds = 0 <= r < len(grid)
68102
col_inbounds = 0 <= c < len(grid[0])
69103

70104
return row_inbounds and col_inbounds
105+
106+
"""
107+
Time and Space Complexities:
108+
109+
- Time Complexity: O(r * c) where r is the number of rows and c is the number of columns in the grid. This is because each cell is processed a constant number of times.
110+
- Space Complexity: O(r * c) for the visited set and the queue, as we might need to store all the cells in the worst case.
111+
112+
Further Notes:
113+
- Approach:
114+
- The algorithm uses Depth-First Search (DFS) to identify the first island.
115+
- Breadth-First Search (BFS) is then used to find the shortest bridge to another island by traversing water cells.
116+
- The BFS ensures that the shortest path is found due to its level-wise exploration.
117+
- Reasoning:
118+
- Starting with DFS helps in identifying all connected cells of the first island.
119+
- BFS is optimal for finding the shortest path in an unweighted grid, which is why it is used after identifying the first island.
120+
"""

0 commit comments

Comments
(0)

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