Treasure Island Adventure (C language) (DFS + BFS)

Treasure Island Adventure

Diaoyu Islands is composed of a main island and several affiliated islands, small hum decided to go to the Diaoyu Islands adventure. The following two-dimensional matrix 10 * 10 is an aerial map of the Diaoyu Islands. FIG digital elevation showing, 0 marine, land represents 1 to 9. Small hum of the aircraft will land at (6,8), and now need to calculate the area of ​​a small island where the hum landed (ie, the number of grid).

A method (BFS using a queue)

#include <stdio.h>
struct note{
	int x;
	int y;
};
int main()
{
	struct note que[2501];
	int head=1,tail=1;
	int a[51][51],book[51][51];
	int n,m,startx,starty,tx,ty,k,i,j;
	
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	scanf("%d %d %d %d",&n,&m,&startx,&starty);
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			scanf("%d",&a[i][j]);
	que[tail].x=startx;
	que[tail].y=starty;
	tail++;
	book[startx][starty]=1;
	int sum=1;
	
	while(head<tail)
	{
		for(k=0;k<4;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(book[tx][ty]==0&&a[tx][ty]>0)
			{
				book[tx][ty]=1;
				que[tail].x=tx;
				que[tail].y=ty;
				sum++;
				tail++;
			}
		}
		head++;
	}
	printf("%d",sum);
	return 0;
}

Method II (DFS):

#include <stdio.h>
int book[51][51],a[51][51];
int m,n,sum ;
void DFS(int x,int y )
{
	int k,tx,ty;
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	for(k=0;k<4;k++)
	{
		tx=x+next[k][0];
		ty=y+next[k][1];
		if(tx<1||ty<1||tx>n||ty>m)
			continue;
		if(book[tx][ty]==0&&a[tx][ty]>0)
		{
			sum++;
			book[tx][ty]=1;
			DFS(tx,ty);
		}
	}
}
int main()
{
	int startx,starty,i,j;
	scanf("%d %d %d %d",&n,&m,&startx,&starty);
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			scanf("%d",&a[i][j]);
	book[startx][starty]=1;
	sum=1;
	DFS(startx,starty);
	printf("%d",sum);
	return 0;
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20200302204515815.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BVWkhBTkdZVQ==,size_16,color_FFFFFF,t_70)

Released seven original articles · won praise 2 · Views 129

Guess you like

Origin blog.csdn.net/PUZHANGYU/article/details/104619271