# 【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

【解析】

【Java代码：DFS、递归】

public class Solution {
private int m, n;

public int numIslands(char[][] grid) {
m = grid.length;
if (m == 0) return 0;
n = grid[0].length;
if (n == 0) return 0;

int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != '1') continue;

ans++;
dfs(grid, i, j);
}
}
return ans;
}

public void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n) return;

if (grid[i][j] == '1') {
grid[i][j] = '2';
dfs(grid, i – 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j – 1);
dfs(grid, i, j + 1);
}
}
}

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

### 1 评论

1. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Metropol Halı Karaca Halı Öztekin ve Selçuklu Halı Cami Halısı ve Cami Halıları Türkiye’nin En Büyük Cami Halısı Fabrikasıyız…