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

200. Number of Islands

时间:2017-02-02 11:16:12      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:clear   vector   content   ota   ++   span   http   row   gif   

200. Number of Islands

  • Total Accepted: 85982
  • Total Submissions: 263924
  • Difficulty: Medium
  • Contributors: Admin

 

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     int numIslands(vector<vector<char>>& grid) {
 4         // Write your code here
 5         if(grid.size() == 0 || grid[0].size() == 0) return 0;
 6         int res = 0;
 7         int m = grid.size();
 8         int n = grid[0].size();
 9         vector<vector<bool>> isVisit(m, vector<bool>(n, false));
10         for(int i = 0; i < m; i++){
11             for(int j = 0; j < n; j++){
12                 if(isVisit[i][j] == false && grid[i][j] == 1){
13                     res++;
14                     dfs(grid, isVisit, i, j);
15                 }
16             }
17         }
18         return res;
19     }
20     void dfs(vector<vector<char>>& grid, vector<vector<bool>>& isVisit, int x, int y){
21         //isVisit[x][y] = true;
22         if (x < 0 || x >= grid.size()) return;
23         if (y < 0 || y >= grid[0].size()) return;
24         if (grid[x][y] != 1 || isVisit[x][y]) return;
25         isVisit[x][y] = true;
26         dfs(grid, isVisit, x + 1, y);
27         dfs(grid, isVisit, x - 1, y);
28         dfs(grid, isVisit, x, y + 1);
29         dfs(grid, isVisit, x, y - 1);
30     }
31 };
View Code

 

 

 

200. Number of Islands

标签:clear   vector   content   ota   ++   span   http   row   gif   

原文地址:http://www.cnblogs.com/93scarlett/p/6360953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!