每日一算法题-寻找岛屿

203 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

一、题目

描述

给一个01矩阵,1代表是陆地,0代表海洋, 如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
岛屿: 相邻陆地可以组成一个岛屿(相邻:上下左右) 判断岛屿个数。

image.png

#include <iostream>
using namespace std;

int island(vector<vector<char> >& grid)
{

}

int main(int, char**)
{
    vector<vector<char> > grid = {{'1','1','0','0','0'},{'0','1','0','1','1'},{'0','0','0','1','1'},{'0','0','0','0','0'},{'0','0','1','1','1'}};
    
    cout << "island count: " << island(grid) << endl;
    
    return 0;
}

二、分析

由题意可知,岛屿就是相邻的1,要把一块岛屿找出来,只需要对第一个找到的1就行上下左右4个方向进行遍历,是1就继续递归,是0就停止。
在遍历过程中,由于递归是上下左右4个方向进行,所以很有可能往回走,所以我们需要一个额外的标识数组用来记录我们遍历时所走过的路,走过的路就不能再走了。

三、模拟

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]

四、实现

void islandDfs(vector<vector<char> >& grid, int row, int col)
{
    if(grid[row][col] == '0') return;
    grid[row][col] = '0';
    if(row > 0){
        islandDfs(grid, row - 1, col);
    }
    if(col > 0){
        islandDfs(grid, row, col - 1);
    }
    if(row < grid.size() - 1){
        islandDfs(grid, row + 1, col);
    }
    if(col < grid.at(0).size() - 1){
        islandDfs(grid, row, col + 1);
    }
}

int island(vector<vector<char> >& grid)
{
    if(grid.empty() || grid.at(0).empty()) return 0;
    int count = 0;
    for(int row = 0; row < grid.size(); ++row){
        for(int col = 0; col < grid.at(0).size(); ++col){
            if(grid[row][col] == '1'){
                ++count;
                islandDfs(grid, row, col);
            }
        }
    }
    return count;
}

五、结言

岛屿问题在搜索类问题也属于一个基础算法,一个个基础的积累都是日后的助力。

创作不易,留个赞再走吧!如果对文章内容有任何指正,欢迎评论!