
[LeetCode] 200. Number of Islands
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

class Solution(object):
def numIslands(self, grid):
if not grid:
return 0
m, n = len(grid), len(grid[0])
count = 0
def dfs(x, y):
if x < 0 or y < 0 or x >= m or y >= n or grid[x][y] == '0':
return
grid[x][y] = '0' # visited
dfs(x+1 ,y) # Up
dfs(x-1 ,y) # Down
dfs(x, y+1) # Right
dfs(x, y-1) # Left
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i, j)
count += 1
return count