Open sophryu99 opened 1 year ago
DFS Approach
from collections import deque
class Solution:
def numIslands(self, grid):
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j) # turn the adjancent '1' to '0'
count += 1
return count
def dfs(self, grid, i, j):
grid[i][j] = 0 # Mark as visited
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
for dr, dc in directions:
nr, nc = i + dr, j + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == '1':
self.dfs(grid, nr, nc)
N: number of elements, M: length of each elements
-Time Complexity: O(N*M)
Visiting every elements in the grid at most once
-Space Complexity: O(1)
No extra memory used
200. Number of Islands
https://leetcode.com/problems/number-of-islands/description/
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
BFS Approach
grid[i][j]
, initiate bfs if it is 1.grid[i][j]
by flipping the '1' value to 0.N: number of elements, M: length of each elements
O(N*M)
Visiting every elements in the grid at most onceO(N*M)
Queue size