Leetcode 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:

11110 
11010
11000
00000

Answer: 1

Example 2:

11000 
11000
00100
00011

Answer: 3

 

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

 

posted @ 2016-05-20 22:43  琴影  阅读(148)  评论(0编辑  收藏  举报