Skip to content

Commit 94dc3c8

Browse files
committed
Number of Islands
1 parent 24faa73 commit 94dc3c8

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

200 Number of Islands.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
3+
4+
Example 1:
5+
6+
11110
7+
11010
8+
11000
9+
00000
10+
Answer: 1
11+
12+
Example 2:
13+
14+
11000
15+
11000
16+
00100
17+
00011
18+
Answer: 3
19+
'''
20+
21+
class Solution(object):
22+
def numIslands(self, grid):
23+
"""
24+
:type grid: List[List[str]]
25+
:rtype: int
26+
"""
27+
if not grid:
28+
return 0
29+
n = len(grid)
30+
m = len(grid[0])
31+
32+
def dfs(i, j):
33+
if 0 <= i < n and 0 <= j < m and grid[i][j] == '1':
34+
grid[i][j] = '0'
35+
dfs(i, j - 1)
36+
dfs(i, j + 1)
37+
dfs(i - 1, j)
38+
dfs(i + 1, j)
39+
return 1
40+
return 0
41+
42+
count = sum(dfs(i, j) for i in range(n) for j in range(m))
43+
return count
44+
45+
46+
if __name__ == "__main__":
47+
assert Solution().numIslands([['1', '1', '0', '0', '0'],
48+
['1', '1', '0', '0', '0'],
49+
['0', '0', '1', '0', '0'],
50+
['0', '0', '0', '1', '1']]) == 3

0 commit comments

Comments
 (0)