# [LeetCode] Number of Islands

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```

Example 2:

```11000 11000 00100 00011```

# 实现代码

```//Runtime:13ms class Solution { public: int numIslands(vector<vector<char>> &grid) { if (grid.empty() || grid[0].empty()) return 0; int row = grid.size(); int col = grid[0].size(); int cnt = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == '1') { cnt++; dfs(grid, i, j); } } } return cnt; } private: void dfs(vector<vector<char>> &grid, int row, int col) { if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] != '1') { return; } ```

``` grid[row][col] = 'X'; dfs(grid, row, col + 1); dfs(grid, row + 1, col); dfs(grid, row, col - 1); dfs(grid, row - 1, col); } };```

1. 本站所有资源来源于用户上传和网络，如有侵权请邮件联系站长！
2. 分享目的仅供大家学习和交流，您必须在下载后24小时内删除！
3. 不得使用于非法商业用途，不得违反国家法律。否则后果自负！
4. 本站提供的源码、模板、插件等等其他资源，都不包含技术服务请大家谅解！
5. 如有链接无法下载、失效或广告，请联系管理员处理！
6. 本站资源售价只是赞助，收取费用仅维持本站的日常运营所需！
7. 如遇到加密压缩包，请使用WINRAR解压,如遇到无法解压的请联系管理员！