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;
}
节选自啊哈磊《啊哈!算法》!