码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Number of Islands

时间:2015-04-08 14:31:36      阅读:122      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!