Movatterモバイル変換


[0]ホーム

URL:


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

Commit72ac563

Browse files
authored
Uncomment and rename BFS solution
1 parent767318a commit72ac563

File tree

1 file changed

+34
-33
lines changed

1 file changed

+34
-33
lines changed

‎python/200-Number-of-Islands.py

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -29,37 +29,38 @@ def dfs(r, c):
2929
returnislands
3030

3131

32-
# BFS Version From Video
32+
# BFS Version From Video
33+
classSolutionBFS:
34+
defnumIslands(self,grid:List[List[str]])->int:
35+
ifnotgrid:
36+
return0
37+
38+
rows,cols=len(grid),len(grid[0])
39+
visited=set()
40+
islands=0
41+
42+
defbfs(r,c):
43+
q=deque()
44+
visited.add((r,c))
45+
q.append((r,c))
46+
47+
whileq:
48+
row,col=q.popleft()
49+
directions= [[1,0],[-1,0],[0,1],[0,-1]]
50+
51+
fordr,dcindirections:
52+
r,c=row+dr,col+dc
53+
if (r)inrange(rows)and (c)inrange(cols)andgrid[r][c]=='1'and (r ,c)notinvisited:
54+
55+
q.append((r ,c ))
56+
visited.add((r,c ))
57+
58+
forrinrange(rows):
59+
forcinrange(cols):
60+
61+
ifgrid[r][c]=="1"and (r,c)notinvisited:
62+
bfs(r,c)
63+
islands+=1
64+
65+
returnislands
3366

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp