https://leetcode.com/problems/number-of-islands/css
Given a 2d grid map of '1'
s (land) and '0'
s (water), count 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.ide
Example 1:spa
Input: 11110 11010 11000 00000 Output: 1
Example 2:code
Input: 11000 11000 00100 00011 Output: 3
1 class Solution: 2 def numIslands(self, grid: List[List[str]]) -> int: 3 if not grid: 4 return 0 5 6 self.x = len(grid) 7 self.y = len(grid[0]) 8 count = 0 9 10 for i in range(self.x): 11 for j in range(self.y): 12 if grid[i][j] == '1': 13 self.DFS(grid, i, j) 14 count += 1 15 16 return count 17 18 def DFS(self, g: List[List[str]], x: int, y: int): 19 if x < 0 or x >= self.x or y < 0 or y >= self.y or g[x][y] == '0': 20 return 21 22 g[x][y] = '0' 23 24 self.DFS(g, x - 1, y) 25 self.DFS(g, x + 1, y) 26 self.DFS(g, x, y - 1) 27 self.DFS(g, x, y + 1)