Created
November 1, 2018 09:18
-
-
Save alxfv/04c8e2eeec252aeafd9b6625b7c19eff to your computer and use it in GitHub Desktop.
Island Count
This file contains 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
def mark_island(grid, i, j): | |
if i >= 0 and j >= 0 and i < len(grid) and j < len(grid[i]) and grid[i][j] == 1: | |
grid[i][j] = 0 | |
mark_island(grid, i, j+1) | |
mark_island(grid, i+1, j) | |
mark_island(grid, i, j-1) | |
mark_island(grid, i-1, j) | |
def get_number_of_islands(grid): | |
count = 0 | |
m = len(grid) | |
n = len(grid[0]) | |
# go by rows | |
for i in range(m): | |
# go by columns | |
for j in range(n): | |
if grid[i][j] == 1: | |
# mark it | |
mark_island(grid, i, j) | |
count += 1 | |
# return mark - 2 | |
return count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment