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



200. Number of Islands(DFS)

遇到1 ,就dfs 吃掉他的邻居。

 

 1 class Solution {
 2 public:
 3     int numIslands(vector<vector<char>>& grid) {
 4         if(grid.size()==0) return 0;
 5         int cnt =0;
 6         for(int i =0;i<grid.size();i++)
 7             for(int j = 0;j <grid[0].size();j++){
 8                 cnt+=grid[i][j]-'0';
 9                 dfs(grid,i,j);
10             }
11         return cnt;   
12     }
13     void dfs(vector<vector<char>>& grid,int x,int y ){
14         if(x>= grid.size()||y>=grid[0].size()||x<0||y<0||grid[x][y]=='0') return ;
15         grid[x][y] = '0';
16         dfs( grid,x-1,y);
17         dfs( grid,x+1,y);
18         dfs( grid,x,y-1);
19         dfs( grid,x,y+1);
20     }
21 };

 

 

 

http://zxi.mytechroad.com/blog/searching/leetcode-200-number-of-islands/


相关文章:

  • 2021-04-21
  • 2022-01-08
  • 2021-08-14
  • 2021-07-31
  • 2021-09-02
  • 2022-03-10
猜你喜欢
  • 2021-12-22
  • 2021-10-09
  • 2021-05-20
相关资源
相似解决方案