Skip to content

Commit

Permalink
problem 200
Browse files Browse the repository at this point in the history
  • Loading branch information
nettee committed Apr 17, 2020
1 parent 95e49fc commit eec0d19
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
Binary file added 0200-Number-of-Islands/Animation/Animation.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 0200-Number-of-Islands/Animation/Animation.m4v
Binary file not shown.
84 changes: 84 additions & 0 deletions 0200-Number-of-Islands/Article/0200-Number-of-Islands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# LeetCode 图解 | 200. 岛屿数量

## 题目描述

给定一个由 `'1'`(陆地 `'0'`(组成的的二维网格计算岛屿的数量一个岛被水包围并且它是通过水平方向或垂直方向上相邻的陆地连接而成的你可以假设网格的四个边均被水包围

**示例 1:**

```
输入:
11110
11010
11000
00000

输出: 1
```

**示例 2:**

```
输入:
11000
11000
00100
00011

输出: 3
```

## 题目解析

这道题的主要思路是深度优先搜索每次走到一个是 1 的格子就搜索整个岛屿

网格可以看成是一个无向图的结构每个格子和它上下左右的四个格子相邻如果四个相邻的格子坐标合法且是陆地就可以继续搜索

在深度优先搜索的时候要注意避免重复遍历我们可以把已经遍历过的陆地改成 2这样遇到 2 我们就知道已经遍历过这个格子了不进行重复遍历

每遇到一个陆地格子就进行深度优先搜索最终搜索了几次就知道有几个岛屿

## 动画理解

![](../Animation/Animation.gif)

## 参考代码

```Java
class Solution {
public int numIslands(char[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}

int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
dfs(grid, r, c);
count++;
}
}
}
return count;
}

void dfs(char[][] grid, int r, int c) {
if (!(0 <= r && r < grid.length && 0 <= c && c < grid[0].length)) {
return;
}
if (grid[r][c] != '1') {
return;
}
grid[r][c] = '2';
dfs(grid, r - 1, c);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
dfs(grid, r, c + 1);
}
}
```

## 复杂度分析

设网格的边长为 $n$则时间复杂度为 $O(n^2)$

0 comments on commit eec0d19

Please sign in to comment.