首页 > 代码库 > 200. Number of Islands
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。