200. Number of Islands
Medium
Problem:
Input:
11110
11010
11000
00000
Output: 1Input:
11000
11000
00100
00011
Output: 3Solution:
DFS
BFS
Last updated
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
def dfs(i, j):
# If it's no longer a land, exit
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = 0
# Search north, south, east and west
dfs(i + 1, j)
dfs(i - 1, j)
dfs(i, j + 1)
dfs(i, j - 1)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i, j)
# After searching all the lands, increase count
count += 1
return countimport collections
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# Exception
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
visit = set()
islands = 0
def bfs(r, c):
q = collections.deque()
visit.add((r, c))
q.append((r, c))
while q:
row, col = q.popleft() # DFS -> q.pop()
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for dr, dc in directions:
r, c = row + dr, col + dc
if (r in range(rows) and c in range(cols) and grid[r][c] == "1" and (r, c) not in visit):
q.append((r, c))
visit.add((r, c))
for r i range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in visit:
bfs(r, c)
islands += 1
return islands