200. Number of Islands(DFS)
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.Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
class Solution: def numIslands(self, grid: List[List[str]]) -> int: def dfs(grid,i,j): if i < 0 or j < 0 or i >= len(grid) or j >=len(grid[0]): return if grid[i][j] == '0': return grid[i][j] ='0' dfs(grid,i+1,j) dfs(grid,i,j+1) dfs(grid,i-1,j) dfs(grid,i,j-1) cnt = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': cnt+=1 dfs(grid,i,j) return cnt
1 class Solution { 2 public int numIslands(char[][] grid) { 3 if(grid==null) return 0; 4 int cnt =0; 5 for(int i =0;i<grid.length;i++){ 6 for(int j =0;j<grid[0].length;j++){ 7 if(grid[i][j]=='1'){ 8 dfs(grid,i,j); 9 cnt++; 10 } 11 } 12 } 13 return cnt; 14 } 15 private void dfs(char[][] grid,int i,int j){ 16 if(i<0||j<0||i>=grid.length||j>=grid[0].length||grid[i][j]=='0') return ; 17 grid[i][j] = '0'; 18 dfs(grid,i-1,j); 19 dfs(grid,i+1,j); 20 dfs(grid,i,j+1); 21 dfs(grid,i,j-1); 22 } 23 24 }