mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
feat(work): add solutions for number-of-islands, pacific-atlantic-water-flow, and clone-graph problems
This commit is contained in:
1 parent
7c5061dcd1
commit
cafc8a4c25
3 files changed
+210
-7
No files matched your search
@@ -12,7 +12,7 @@ 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.
|
||||
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
@@ -34,19 +34,39 @@ Input: grid = [
|
||||
]
|
||||
Output: 3
|
||||
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• m == grid.length
|
||||
• m == grid.length
|
||||
|
||||
• n == grid[i].length
|
||||
• n == grid[i].length
|
||||
|
||||
• 1 <= m, n <= 300
|
||||
• 1 <= m, n <= 300
|
||||
|
||||
• grid[i][j] is '0' or '1'.
|
||||
• grid[i][j] is '0' or '1'.
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def numIslands(self, grid: List[List[str]]) -> int:
|
||||
|
||||
rows, cols = len(grid), len(grid[0])
|
||||
|
||||
def dfs(r, c):
|
||||
if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
|
||||
return
|
||||
else:
|
||||
grid[r][c] = "0"
|
||||
dfs(r, c + 1) # right
|
||||
dfs(r + 1, c) # bottom
|
||||
dfs(r, c - 1) # left
|
||||
dfs(r - 1, c) # top
|
||||
|
||||
num_islands = 0
|
||||
for r in range(rows):
|
||||
for c in range(cols):
|
||||
if grid[r][c] == "1":
|
||||
num_islands += 1
|
||||
dfs(r, c)
|
||||
|
||||
return num_islands
|
||||
Reference in new issue
Block a user