首页 > 其他 > 详细

[LeetCode] Number of Islands

时间:2015-04-08 14:28:56      阅读:262      评论: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

没什么,DFS就好了。

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

 

[LeetCode] Number of Islands

原文:http://www.cnblogs.com/easonliu/p/4402077.html

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