# LeetCode：Number of Islands - 统计岛屿数量

2017/09/26 13:52

1、题目名称

Number of Islands（统计岛屿数量）

2、题目地址

https://leetcode.com/problems/number-of-islands/description/

3、题目内容

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

4、解题方法

/**
* LeetCode 200 - Number of Islands
* @文件名称 Solution.java
* @文件作者 Tsybius2014
* @创建时间 2017年9月26日11:10:25
*/
class Solution {

/**
* 统计岛屿数量
* @param grid
* @return
*/
public int numIslands(char[][] grid) {

if (grid.length == 0 || grid[0].length == 0) {
return 0;
}

int num = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
destroyIsland(grid, i, j);
num++;
}
}
}

return num;
}

/**
* 将当前陆地从区域内抹去
* @param grid
* @param i
* @param j
*/
private void destroyIsland(char[][] grid, int i, int j) {
grid[i][j] = '0';
if (i != 0 && grid[i -1][j] == '1') {
destroyIsland(grid, i - 1, j);
}
if (i != grid.length - 1 && grid[i + 1][j] == '1') {
destroyIsland(grid, i + 1, j);
}
if (j != 0 && grid[i][j - 1] == '1') {
destroyIsland(grid, i, j - 1);
}
if (j != grid[0].length - 1 && grid[i][j + 1] == '1') {
destroyIsland(grid, i, j + 1);
}
}

}

END

0
0 收藏

0 评论
0 收藏
0