Skip to content

Commit 8bbc0f4

Browse files
authored
Merge pull request #2 from sfuSwSo/200-number-of-islands
solution for problem 200
2 parents 6d18055 + 0966346 commit 8bbc0f4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: 200-number-of-islands/solution.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
def numIslands(self, grid: List[List[str]]) -> int:
3+
m = len(grid)
4+
n = len(grid[0])
5+
count = 0
6+
visited = set()
7+
directions=[(-1,0),(0,1),(1,0),(0,-1)]
8+
9+
def islands(x,y):
10+
for dx, dy in directions:
11+
nx,ny = x+dx, y+dy
12+
if 0<=nx<m and 0<=ny<n and grid[nx][ny]=='1' and (nx,ny) not in visited:
13+
visited.add((nx,ny))
14+
islands(nx,ny)
15+
16+
17+
for x in range(m):
18+
for y in range(n):
19+
if grid[x][y] == '1' and (x,y) not in visited:
20+
count +=1
21+
visited.add((x,y))
22+
islands(x,y)
23+
24+
return count
25+
26+
27+
28+
29+
30+
31+
32+
33+
34+
35+
36+
37+

0 commit comments

Comments
 (0)