Problem : https://leetcode.com/problems/number-of-islands/
Use counter as flag to mark visited position.
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row = len(grid)
if not row:
return 0
column = len(grid[0])
count = 2
def dfs(y, x, mark):
if y < 0 or y >= row:
return
if x < 0 or x >= column:
return
if grid[y][x] == "1":
grid[y][x] = mark
dfs(y-1, x, mark)
dfs(y+1, x, mark)
dfs(y, x-1, mark)
dfs(y, x+1, mark)
for y in range(row):
for x in range(column):
if grid[y][x] == "1":
dfs(y, x, str(count))
count += 1
return count - 2
No comments:
Post a Comment