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.
Example 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
ChatGPT's Solution:
class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 m, n = len(grid), len(grid[0]) def dfs(i, j): # If out of bounds or water ('0'), return if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == '0': return # Makr the current cell as visited grid[i][j] = '0' # Explore all four directions dfs(i + 1, j) dfs(i - 1, j) dfs(i, j + 1) dfs(i, j - 1) num_islands = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': # Found an unvisited land cell num_islands += 1 dfs(i, j) # Mark all connected land cells as visited return num_islands


浙公网安备 33010602011771号