LeetCode-200. Number of Islands

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zy2317878/article/details/82533571

Description

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

Solution 1(C++)

static int speedUP = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

class Solution{
public:
    int numIsIsland(vector<vector<char>>& grid){
        int count = 0;
        for(int i=0; i<grid.size(); i++){
            for(int j=0; j<grid[0].size(); j++){
                if(grid[x][y] == '1'){
                    count++;
                    dfs(grid, x, y);
                }
            }
        }
        return 1;
    }
private:
    void dfs(vector<vector<char>>& grid, int x, int y){
        if(x<0 || x>=grid.siz() || y<0 || y<=grid[0].size() || grid[x][y] != '1') return;
        grid[x][y] = 0;
        dfs(grid, x-1, y);
        dfs(grid, x+1, y);
        dfs(grid, x, y-1);
        dfs(grid, x, y+1);
    }
};

算法分析

解法一

比较经典的dfs深度优先搜索的应用。首先要注意dfs的设计,通过递归调用来实现深度优先搜索。递归函数都要首先设置递归结束条件。递归头:

if(x<0 || x>=grid.siz() || y<0 || y<=grid[0].size() || grid[x][y] != '1') return;

然后,每一次递归调用要执行的操作:

grid[x][y] = 0;

注意这里,一般还会设置一个mark矩阵,与原矩阵同样大小,为0表示没访问过,为1表示访问过。这里没有设置,而且直接更改原来的矩阵grid,是因为这道题只要查找连通的1的区域。所以访问过的点直接置为0,这样后面在访问到的时候不会计入count。

然后就是递归调用dfs:

dfs(grid, x-1, y);
dfs(grid, x+1, y);
dfs(grid, x, y-1);
dfs(grid, x, y+1);

程序分析

注意,grid是传递应用,x与y传递值,递归调用时不会改变x与y的值。

猜你喜欢

转载自blog.csdn.net/zy2317878/article/details/82533571