Leetcode 200. Number of Islands

Posted 琴影

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于Leetcode 200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

leetcode200 Number of Islands

Leetcode 200. Number of Islands

[leetcode-200-Number of Islands]

leetcode 200. Number of Islands

leetcode--200. Number of Islands

[LeetCode] 200. Number of Islands(岛屿的数目)