题目:
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: 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
解题思路
代码:
Java
class Solution {//dfspublic int numIslands(char[][] grid) {int cnt=0;for(int i=0;i<grid.length;++i){for(int j=0;j<grid[0].length;++j){if(grid[i][j]=='1'){dfsFill(grid,i,j);cnt+=1;}}}return cnt;}private void dfsFill(char[][] grid,int i,int j){if(i<0||j<0||i>=grid.length||j>=grid[0].length||grid[i][j]!='1') return;grid[i][j]='0';dfsFill(grid,i+1,j);dfsFill(grid,i-1,j);dfsFill(grid,i,j+1);dfsFill(grid,i,j-1);}
}
Python
class Solution:def numIslands(self, grid: List[List[str]]) -> int:if not grid:return 0cnt=0for i in range(len(grid)):for j in range(len(grid[0])):if grid[i][j]=='1':self.dfs(grid,i,j)cnt+=1return cntdef 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':returngrid[i][j]='0'self.dfs(grid,i+1,j)self.dfs(grid,i-1,j)self.dfs(grid,i,j+1)self.dfs(grid,i,j-1)