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 4c7280c

Browse files
Merge pull request #344 from MoigeMatino/fix-best-bridge
fix: fix bug in best bridge
2 parents 7bb8f63 + fd63c1b commit 4c7280c

File tree

1 file changed

+40
-82
lines changed

1 file changed

+40
-82
lines changed

‎graphs/best_bridge/best_bridge.py

Lines changed: 40 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,112 +1,70 @@
1+
from typing import List, Set
12
from collections import deque
23

3-
def best_bridge(grid):
4-
"""
5-
Finds the shortest distance between two islands on the grid.
4+
def best_bridge(grid:List[List]) -> int:
5+
visited = set()
66

7-
Args:
8-
grid (List[List[str]]): A 2D grid representing the islands where 'L' represents land and 'W' represents water.
9-
10-
Returns:
11-
int: The shortest distance between the two islands.
12-
13-
"""
14-
# Find the first island for traversal
157
for r in range(len(grid)):
168
for c in range(len(grid[0])):
17-
island = find_island(grid, r, c, set())
9+
island = find_island(grid, r, c, visited)
1810
if len(island) > 0:
19-
first_island = island
2011
break
12+
if len(island) > 0:
13+
first_island = island
14+
print(first_island)
15+
break
16+
if len(island) == 0:
17+
return "No island in sight"
2118

22-
visited = set(first_island)
23-
queue = deque([ ])
24-
for pos in visited:
19+
queue = deque([])
20+
for pos in first_island:
2521
r, c = pos
26-
queue.append((r,c,0))
27-
# begin BFS traversal
22+
queue.append((r, c, 0))
23+
24+
newly_visited = set()
25+
2826
while queue:
2927
r, c, distance = queue.popleft()
30-
31-
# If a land cell is found and it's not part of the first island, return the distance
28+
pos=r, c
29+
3230
if grid[r][c] == "L" and pos not in first_island:
3331
return distance - 1
3432

35-
deltas = [(1, 0), (-1, 0), (0, 1), (0, -1)]
36-
33+
deltas = [(1,0), (-1,0), (0,1), (0, -1)]
3734
for delta in deltas:
3835
delta_r, delta_c = delta
39-
neighbor_row = r + delta_r
40-
neighbor_col = c + delta_c
41-
neighbor_pos = (neighbor_row, neighbor_col)
36+
neighbor_r = delta_r + r
37+
neighbor_c = delta_c + 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))
4242

43-
if inbounds(grid, neighbor_row, neighbor_col) and neighbor_pos not in visited:
44-
visited.add(pos)
45-
queue.append((neighbor_row, neighbor_col, distance +1))
43+
return -1
4644

47-
def inbounds(grid, r, c):
48-
"""
49-
Checks if a given position is within the bounds of the grid.
50-
51-
Args:
52-
grid (List[List[str]]): A 2D grid representing the islands.
53-
r (int): The row index.
54-
c (int): The column index.
55-
56-
Returns:
57-
bool: True if the position is within the grid bounds, False otherwise.
58-
"""
59-
row_inbounds = 0 <= r < len(grid)
60-
col_inbounds = 0 <= c < len(grid[0])
61-
return row_inbounds and col_inbounds
6245

63-
def find_island(grid, r, c, visited):
64-
"""
65-
Finds all positions of the island connected to the given position.
66-
67-
Args:
68-
grid (List[List[str]]): A 2D grid representing the islands.
69-
r (int): The row index.
70-
c (int): The column index.
71-
visited (set): A set of visited positions.
72-
73-
Returns:
74-
set: A set of positions belonging to the island connected to the given position.
75-
"""
76-
if not inbounds(grid, r, c) or grid[r][c] == 'W':
46+
def find_island(grid:List[List], r:int, c:int, visited:Set) -> Set:
47+
if not inbounds(grid, r, c):
7748
return visited
7849

79-
pos = (r,c)
80-
50+
if grid[r][c] == "W":
51+
return visited
52+
53+
pos = r, c
8154
if pos in visited:
8255
return visited
8356

8457
visited.add(pos)
8558

86-
find_island(grid, r - 1, c, visited)
87-
find_island(grid, r + 1, c, visited)
88-
find_island(grid, r, c-1, visited)
59+
find_island(grid, r+1, c, visited)
60+
find_island(grid, r-1, c, visited)
8961
find_island(grid, r, c+1, visited)
62+
find_island(grid, r, c-1, visited)
9063

91-
"""
92-
Time Complexity Analysis:
93-
- Finding the first island: O(r*c), where r is number of rows and c is number of columns in the grid.
94-
- BFS traversal to find the shortest distance between islands: O(e), where e is the number of edges (neighbors) of the islands.
95-
Overall: O(r*c + e)
64+
return visited
9665

97-
Space Complexity Analysis:
98-
- Storing visited nodes: O(r*c), where n is the size of the grid.
99-
- Storing nodes being visited: O(r*c).
100-
Overall: O(r*c)
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])
10169

102-
FURTHER NOTES:
103-
This algorithm first finds one island using depth-first search (DFS) traversal. It then performs a breadth-first search (BFS)
104-
traversal to find the shortest distance between this island and the nearest 'L' (land) cells that are not part of the first island.
105-
The algorithm iterates through each cell in the grid to find the first island, and then conducts BFS to find the shortest distance
106-
between the first island and the nearest land cells. This approach efficiently utilizes DFS for island discovery and BFS for distance calculation.
107-
The 'distance - 1' adjustment is made to account for the fact that the BFS traversal starts from the initial island. When the BFS encounters the
108-
first land cell outside of this island, it calculates the distance from the starting point of the traversal (which is part of the initial island)
109-
to this land cell. Since the distance represents the number of steps taken in the traversal, subtracting 1 ensures that the returned distance
110-
corresponds to the distance between the two islands, excluding the starting land cell. Therefore, distance - 1 ensures that the calculated distance
111-
accurately reflects the shortest distance between the two islands.
112-
"""
70+
return row_inbounds and col_inbounds

0 commit comments

Comments
(0)

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