Leetcode 200
How to count islands on a grid
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.
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.
Source
python
1class Solution(object):2 # The idea is if we found a 1, means that we found an island3 # so we have to paint every part of it. That DFS will end when4 # we're surrounded by water, so we must find another island or 15 # in the matrix.6 def numIslands(self, grid):7 """8 :type grid: List[List[str]]9 :rtype: int10 """11 res = 012 for i in range(len(grid)):13 for j in range(len(grid[0])):14 if grid[i][j] == "1":15 res += 116 self.dfs(i,j,grid)17 return res1819 def dfs(self, i, j, grid):20 if i < 0 or j < 0 or i > len(grid) or j > len(grid[0]) or grid[i][j] != "1": return21 grid[i][j] = "#"22 self.dfs(i-1, j, grid)23 self.dfs(i+1, j, grid)24 self.dfs(i, j-1, grid)25 self.dfs(i, j+1, grid)