Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
200: Number of Islands
  • Loading branch information
sumanth-botlagunta committed Mar 23, 2023
commit 53bb26314fc4a99392836e85b8f37f3f70494fb0
24 changes: 24 additions & 0 deletions python/number_of_islands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# https://leetcode.com/problems/number-of-islands/description/
# T: O(MN) where M is the number of rows and N is the number of columns.
# S: O(MN) where M is the number of rows and N is the number of columns.

def numIslands(self, grid):
if not grid:
return 0

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)
count += 1
return count

def dfs(self, grid, i, j):
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '#'
self.dfs(grid, i+1, j)
self.dfs(grid, i-1, j)
self.dfs(grid, i, j+1)
self.dfs(grid, i, j-1)