LeetCode:Number of Islands - 统计岛屿数量

原创
2017/09/26 13:52
阅读数 296

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

中文:

现有一个用二维数组表示的区域,0代表水面,1代表陆地,计算区域内岛屿的数量。

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
分享
返回顶部
顶部