200. Number of Islands
[Medium] “Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands."
Note: good to revisit and re-solve with BFS (TODO:
)
Python3:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if grid == []:
return 0
count = 0
state = grid
width = len(grid[0])
height = len(grid)
def search(x, y):
state[y][x] = 0
# search horizontal
if ((x + 1) < width) and (state[y][x + 1] == "1"):
search(x + 1, y)
if ((x - 1) >= 0) and (state[y][x - 1] == "1"):
search(x - 1, y)
# search vertical
if ((y + 1) < height) and (state[y + 1][x] == "1"):
search(x, y + 1)
if ((y - 1) >= 0) and (state[y - 1][x] == "1"):
search(x, y - 1)
for h in range(height):
for w in range(width):
if state[h][w] == "1":
# search land and mutate state
count += 1
search(w, h)
return count