2018-11-12 leetcode Number of Islands Number of IslandsDFS Version - 148ms 12345678910111213141516171819202122232425class Solution: def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not grid: return 0 count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': self.dfs(grid, i, j) count += 1 return count def dfs(self, grid, i, j): if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1': return grid[i][j] = '#' self.dfs(grid, i+1, j) self.dfs(grid, i-1, j) self.dfs(grid, i, j+1) self.dfs(grid, i, j-1) DFS Map Version - 116ms 12345678910111213class Solution: def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ def sink(i, j): if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and grid[i][j] == '1': grid[i][j] = '0' list(map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))) return 1 return 0 return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[i]))) test code 1234In [429]: n = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]In [430]: s = Solution(); t = s.numIslands(n); print(t)1 leet code Newer Count and Say Older Letter Combinations of a Phone Number