【深搜】计算岛屿数目-华为笔试

题目描述:

输入n行m列二进制来描述一副地图,1代表陆地,0代表海水。如果横列或者竖列相连代表它们同属于一块陆地。
请实现计算陆地个数的算法,示例如下:

输入:

5  4

1  0  1  0

1  1  1  1

1  0  0  0

0  1  0  1

0  0  0  1

输出:

3

矩阵中1代表陆地,0代表海水。我们以行优先的方式遍历整个数组,找到一块陆地后,从找到这块陆地的起点开始,不停递归遍历它的上下左右四个方向,遇到陆地的位置就把它变为海水,每遍历一块陆地count++,最后返回陆地数。

代码如下:

#include<iostream>
using namespace std;

//陆地元素转换海水
void convert(int map[][100],int row,int col,int i,int j){
    if(j-1>=0&&map[i][j-1]==1){ //向左边走
        map[i][j-1]=0;
        convert(map,row,col,i,j-1);
    }
    if(j+1<col&&map[i][j+1]==1){ //向右走
        map[i][j+1]=0;
        convert(map,row,col,i,j+1);
    }
    if(i-1>=0&&map[i-1][j]==1){ //向上边走
        map[i-1][j]=0;
        convert(map,row,col,i-1,j);
    }
    if(i+1<row&&map[i+1][j]==1){ //向下走
        map[i+1][j]=0;
        convert(map,row,col,i+1,j);
    }
}

//返回陆地数
int getIslandCount(int map[][100],int row,int col){
    int count=0;
    for(int i=0;i<row;i++)
	for(int j=0;j<col;j++){
            if(map[i][j]==1){
                map[i][j]=0; //找到这块陆地的起点置0 
            	convert(map,row,col,i,j); //遍历这块陆地并置0 
                count++; //陆地数++ 
	    }
	}
    return count;	
}

int main(){
    int row=0; //行 
    int col=0; //列 
    cin>>row>>col;
    int map[100][100];
    for(int i=0;i<row;i++)
	for(int j=0;j<col;j++)
	    cin>>map[i][j];
    cout<<getIslandCount(map,row,col);
}

制作不易,多多点赞(●'◡'●)!

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jiawen9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值