Skip to content

Commit 70a019f

Browse files
committed
Sync LeetCode submission Runtime - 242 ms (60.36%), Memory - 20.1 MB (44.37%)
1 parent e24c650 commit 70a019f

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

0200-number-of-islands/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p>
2+
3+
<p>An <strong>island</strong> 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.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> grid = [
10+
[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],
11+
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],
12+
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
13+
[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]
14+
]
15+
<strong>Output:</strong> 1
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> grid = [
22+
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
23+
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
24+
[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],
25+
[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;]
26+
]
27+
<strong>Output:</strong> 3
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
<p><strong>Constraints:</strong></p>
32+
33+
<ul>
34+
<li><code>m == grid.length</code></li>
35+
<li><code>n == grid[i].length</code></li>
36+
<li><code>1 &lt;= m, n &lt;= 300</code></li>
37+
<li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
38+
</ul>

0200-number-of-islands/solution.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Approach 1: DFS
2+
3+
# m = no. of rows, n = no. of columns
4+
# Time: O(m * n)
5+
# Space: O(m * n)
6+
7+
class Solution:
8+
def numIslands(self, grid: List[List[str]]) -> int:
9+
if not grid:
10+
return 0
11+
12+
num_islands = 0
13+
for r in range(len(grid)):
14+
for c in range(len(grid[0])):
15+
if grid[r][c] == "1":
16+
self.dfs(grid, r, c)
17+
num_islands += 1
18+
19+
return num_islands
20+
21+
def dfs(self, grid, r, c):
22+
if r < 0 or c < 0 or r >= len(grid) or c >= len(grid[0]) or grid[r][c] != "1":
23+
return
24+
25+
grid[r][c] = "0"
26+
27+
self.dfs(grid, r - 1, c)
28+
self.dfs(grid, r + 1, c)
29+
self.dfs(grid, r, c - 1)
30+
self.dfs(grid, r, c + 1)
31+
32+

0 commit comments

Comments
 (0)