Skip to content

Commit 4ef8de4

Browse files
authored
Merge pull request #1038 from Mark-777-0/patch-1
Adding BFS For Convenience
2 parents 825a25b + 72ac563 commit 4ef8de4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

python/200-Number-of-Islands.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,40 @@ def dfs(r, c):
2727
islands += 1
2828
dfs(r, c)
2929
return islands
30+
31+
32+
# BFS Version From Video
33+
class SolutionBFS:
34+
def numIslands(self, grid: List[List[str]]) -> int:
35+
if not grid:
36+
return 0
37+
38+
rows, cols = len(grid), len(grid[0])
39+
visited=set()
40+
islands=0
41+
42+
def bfs(r,c):
43+
q = deque()
44+
visited.add((r,c))
45+
q.append((r,c))
46+
47+
while q:
48+
row,col = q.popleft()
49+
directions= [[1,0],[-1,0],[0,1],[0,-1]]
50+
51+
for dr,dc in directions:
52+
r,c = row + dr, col + dc
53+
if (r) in range(rows) and (c) in range(cols) and grid[r][c] == '1' and (r ,c) not in visited:
54+
55+
q.append((r , c ))
56+
visited.add((r, c ))
57+
58+
for r in range(rows):
59+
for c in range(cols):
60+
61+
if grid[r][c] == "1" and (r,c) not in visited:
62+
bfs(r,c)
63+
islands +=1
64+
65+
return islands
66+

0 commit comments

Comments
 (0)