Open fockspaces opened 1 year ago
用 recursion travel through all the islands,並將走過的 islands 變成海
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n, count = len(grid), len(grid[0]), 0
def DFS(grid, r, c):
if r < 0 or c < 0 or r >= m or c >= n:
return
if grid[r][c] != '1':
return
grid[r][c] = '0'
DFS(grid, r + 1, c)
DFS(grid, r - 1, c)
DFS(grid, r, c + 1)
DFS(grid, r, c - 1)
for row in range(m):
for col in range(n):
if grid[row][col] == '1':
DFS(grid, row, col)
count += 1
return count
可以更進一步將上下左右用 for loop 表示
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n, count = len(grid), len(grid[0]), 0
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
def DFS(grid, r, c):
if r < 0 or c < 0 or r >= m or c >= n:
return
if grid[r][c] != '1':
return
grid[r][c] = '0'
for dir in directions:
DFS(grid, r + dir[0], c + dir[1])
for row in range(m):
for col in range(n):
if grid[row][col] == '1':
DFS(grid, row, col)
count += 1
return count
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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.
Example 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
Constraints:
m == grid.length n == grid[i].length 1 <= m, n <= 300 grid[i][j] is '0' or '1'.