200. Number of Islands

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

求矩阵中的连通分量数目

C++:dfs
 1 class Solution {
 2 public:
 3     int numIslands(vector<vector<char>>& grid) {
 4         int n = grid.size() ;
 5         if (n == 0)
 6             return 0 ;
 7         int m = grid[0].size() ;
 8         int res = 0 ;
 9         for(int i = 0 ; i < n ; i++){
10             for(int j = 0 ; j < m ; j++){
11                 if (grid[i][j] == '1'){
12                     dfs(grid,i,j) ;
13                     res++ ;
14                 }
15             }
16         }
17         return res ;
18     }
19     void dfs(vector<vector<char>>& grid , int i , int j){
20         if (i >= 0 && i < grid.size() && j >=0 && j < grid[0].size() && grid[i][j] == '1'){
21             grid[i][j] = '0' ;
22             dfs(grid,i+1,j) ;
23             dfs(grid,i-1,j) ;
24             dfs(grid,i,j+1) ;
25             dfs(grid,i,j-1) ;
26         }
27     }
28 };

 

 
posted @ 2019-01-16 16:24  __Meng  阅读(148)  评论(0编辑  收藏  举报