Skip to content

Commit 2c0bffe

Browse files
authored
Create 200_Number_of_Islands.md
1 parent ba25721 commit 2c0bffe

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

200_Number_of_Islands.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
## 200. Number of Islands
2+
3+
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
4+
5+
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.
6+
7+
8+
9+
Example 1:
10+
11+
Input: grid = [
12+
["1","1","1","1","0"],
13+
["1","1","0","1","0"],
14+
["1","1","0","0","0"],
15+
["0","0","0","0","0"]
16+
]
17+
Output: 1
18+
Example 2:
19+
20+
Input: grid = [
21+
["1","1","0","0","0"],
22+
["1","1","0","0","0"],
23+
["0","0","1","0","0"],
24+
["0","0","0","1","1"]
25+
]
26+
Output: 3
27+
28+
29+
Constraints:
30+
31+
m == grid.length
32+
n == grid[i].length
33+
1 <= m, n <= 300
34+
grid[i][j] is '0' or '1'.
35+
36+
37+
```python
38+
def numIslands(self, grid: List[List[str]]) -> int:
39+
r = len(grid)
40+
c = len(grid[0])
41+
42+
count = 0
43+
44+
def dfs(grid, i, j):
45+
46+
47+
if i <0 or j <0 or i>=r or j>=c or grid[i][j] != '1':
48+
return
49+
50+
grid[i][j] = '#'
51+
52+
dfs(grid, i+1, j)
53+
dfs(grid, i-1, j)
54+
dfs(grid, i, j+1)
55+
dfs(grid, i, j-1)
56+
57+
for i in range(r):
58+
for j in range(c):
59+
if grid[i][j] == '1':
60+
dfs(grid, i, j)
61+
count +=1
62+
return count
63+
```
64+
65+
66+
67+
```
68+
Runtime: 132 ms, faster than 86.94% of Python3 online submissions for Number of Islands.
69+
Memory Usage: 15.5 MB, less than 38.11% of Python3 online submissions for Number of Islands.
70+
```

0 commit comments

Comments
 (0)