Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added another solution type #190

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
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
34 changes: 33 additions & 1 deletion Python/number-of-islands.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,46 @@ def dfs(grid, i, j):
count += 1
return count


# Time: O(m * n)
# Space: O(m * n)
# dfs recursive solution
class Solution3(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
ROWS = len(grid)
COLS = len(grid[0])
visited = set()

def dfs(row,col):
if row<0 or row>=ROWS or col<0 or col>=COLS or (row,col) in visited or grid[row][col] == "0":
return
visited.add((row,col))
dfs(row+1,col)
dfs(row-1,col)
dfs(row,col+1)
dfs(row,col-1)

numberOfIslands = 0
for i in range(ROWS):
for j in range(COLS):
if grid[i][j]=="1" and (i,j) not in visited:
dfs(i,j)
numberOfIslands += 1
return numberOfIslands



# Time: O(m * n)
# Space: O(m * n)
import collections


# bfs solution
class Solution3(object):
class Solution4(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
Expand Down