200. Number of Islands
Posted 会咬人的兔子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了200. Number of Islands相关的知识,希望对你有一定的参考价值。
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 };
以上是关于200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章