DFS/BFS解决宝岛探险

DFS宝岛探险


思路:注意此处我们把与小哼降落点上下左右相连接的陆地视为同一岛屿,0表示海洋,1~9表示陆地。计算小哼降落地所在岛的面积(即有多少格子)


#include<cstdio>
#include<iostream>
using namespace std;
int a[51][51];//用来存储地图 
int book[51][51],sum,n,m;
void dfs(int x,int y) {
		//定义一个用于表示走的方向的数组 
		int next[4][2]={
						{0,1},//向右 
						{1,0},//向下 
						{0,-1},//向左 
						{-1,0}};//向上 	
		
		int tx,ty;
		for(int k=0;k<=3;k++) {
			tx=x+next[k][0];
			ty=y+next[k][1];
			
			if(tx<1 || tx>n || ty<1 ||ty >m)
				continue;
			
			if(a[tx][ty]>0 && book[tx][ty]==0) {
				sum++;
				book[tx][ty]=1;
				dfs(tx,ty);
			}
		} 
		return ;
	}
int main() {
	
	int startx,starty;
	cin>>n>>m>>startx>>starty;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			cin>>a[i][j];
	
	book[startx][starty]=1;
	sum=1;
	dfs(startx,starty);	
	printf("%d",sum);
	getchar();getchar();
	return 0; 
	
}


BFS 宝岛探险


#include<cstdio>
#include<iostream>
using namespace std;
struct note {
	int x;
	int y;
};

int main() {
	struct note que[2501];
	int a[51][51];//用来存储地图 
	int book[51][51]={0};
	
	//定义一个用于表示走的方向的数组 
	int next[4][2]={
					{0,1},//向右 
					{1,0},//向下 
					{0,-1},//向左 
					{-1,0}};//向上 
	
	int n,m,startx,starty;
	cin>>n>>m>>startx>>starty;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			cin>>a[i][j];
			
	
	//队列初始化  
	int head=1;
	int tail=1;
	 
	que[tail].x=startx;
	que[tail].y=starty;
	tail++;
	book[startx][starty]=1;
	int sum=1;

	int tx,ty;	
	while(head<tail) {	//当队列不空时候循环 
		for(int k=0;k<=3;k++) {
			//计算下一点坐标
			tx=que[head].x+next[k][0];
			ty=que[head].y+next[k][1];
			
			//判断是否越界 
			if(tx<1 || tx>n|| ty<1 || ty>m)
				continue;
			
			//判断是否为障碍物 或者已经在路径中 
			if(a[tx][ty]>0 && book[tx][ty]==0) {
				sum++;
				book[tx][ty]=1;	//把这个点标记为走过,注意宽搜每个点只入列一次,所以和深搜不同,不需要将book数组还原 
				//插入新的点到队列中 
				que[tail].x=tx;
				que[tail].y=ty;
				tail++;
			
				} 
			}
			head++;//此地方不能忘记,当一个点拓展结束,head++才能对后面的点再进行拓展 
		
	} 
	printf("%d",sum);
	//getchar();getchar();
	return 0; 
	
}

节选自啊哈磊《啊哈!算法》!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值