Created
April 18, 2020 01:13
-
-
Save munguial/430bd9545ab5c07231a5f8851030f82e to your computer and use it in GitHub Desktop.
Day 17 - Number Of Islands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def numIslands(self, grid: List[List[str]]) -> int: | |
result = 0 | |
for row in range(len(grid)): | |
for column in range(len(grid[0])): | |
if grid[row][column] == '1': | |
result += 1 | |
self.dfs(grid, row, column) | |
return result | |
def dfs(self, grid, row, column): | |
grid[row][column] = '0' | |
moves = [[0,1], [1,0], [-1,0], [0,-1]] | |
for move in moves: | |
newRow = row + move[0] | |
newColumn = column + move[1] | |
if self.isValidMove(grid, newRow, newColumn): | |
self.dfs(grid, newRow, newColumn) | |
def isValidMove(self, grid, r, c): | |
if r >= len(grid) or c >= len(grid[0]) \ | |
or r < 0 or c < 0: | |
return False | |
if grid[r][c] == '0': | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment