首页 > 编程语言 > 详细

LeetCode 200. Number of Islands 岛屿数量(C++/Java)

时间:2020-02-12 23:16:19      阅读:102      评论:0      收藏:0      [点我收藏+]

题目:

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

分析:

给定一个二维数组,其中由1(陆地)和0(水)组成,要求岛屿的数量,而岛屿则是陆地间上下左右相连后形成的,斜向的不算相连则构不成岛屿。

遍历整个数组,当元素为1时,岛屿数目加一,此时我们要把所有与这个位置相连的陆地全部变成水(1变成0),然后继续遍历到结尾即可。

程序:

C++

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.size() == 0 || grid[0].size() == 0)
            return 0;
        m = grid.size();
        n = grid[0].size();
        int res = 0;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(grid[i][j] == 1){
                    dfs(grid, i, j);
                    res++;
                }
            }
        }
        return res;
    }
private:
    void dfs(vector<vector<char>>& grid, int i, int j){
        if(i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0)
            return;
        grid[i][j] = 0;
        dfs(grid, i-1, j);
        dfs(grid, i, j-1);
        dfs(grid, i+1, j);
        dfs(grid, i, j+1);
    }
    int m;
    int n;
};

Java

class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length == 0 || grid[0].length == 0)
            return 0;
        m = grid.length;
        n = grid[0].length;
        int res = 0;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(grid[i][j] == ‘1‘){
                    dfs(grid, i, j);
                    res++;
                }
            }
        }
        return res;
    }
    private void dfs(char[][] grid, int i, int j){
        if(i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == ‘0‘)
            return;
        grid[i][j] = ‘0‘;
        dfs(grid, i-1, j);
        dfs(grid, i, j-1);
        dfs(grid, i+1, j);
        dfs(grid, i, j+1);
    }
    private int m;
    private int n;
}

 

LeetCode 200. Number of Islands 岛屿数量(C++/Java)

原文:https://www.cnblogs.com/silentteller/p/12301440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!