首页 > 其他 > 详细

LeetCode OJ:Number of Islands(孤岛计数)

时间:2015-12-08 22:00:50      阅读:167      评论:0      收藏:0      [点我收藏+]

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

计算孤岛的数量,注意上下左右为0就是孤岛,孤岛可以很大,grid范围以外的都算是water。代码如下所示:

 1 class Solution {
 2 public:
 3     int numIslands(vector<vector<char>>& grid) {
 4         int count = 0;
 5         if(!grid.size() || !grid[0].size())
 6             return count;
 7           int row = grid.size();
 8           int col = grid[0].size();
 9           for(int i = 0; i < row; ++i){
10               for(int j = 0; j < col; ++j){
11                   if(grid[i][j] == 1){
12                       dfs(grid, i, j);
13                       count++;
14                   }
15 
16               }
17           }
18           return count;
19     }
20 
21     void dfs(vector<vector<char>> & grid, int x, int y)
22     {
23         if(grid[x][y] == 1)
24             grid[x][y] = X;
25         else 
26             return;
27         dfs(grid, x+1, y);
28         dfs(grid, x-1, y);
29         dfs(grid, x, y+1);
30         dfs(grid, x, y0);
31     }
32 };

 

LeetCode OJ:Number of Islands(孤岛计数)

原文:http://www.cnblogs.com/-wang-cheng/p/5016641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!