迷宫游戏(C语言)(DFS+BFS)

迷宫游戏

方法一(DFS):

#include <stdio.h>
int min=999;
int m,n,p,q;
int a[51][51],book[51][51];
void DFS(int x,int y,int step)
{
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	int tx,ty,k;
	if(x==p&&y==q)
	{
		if(step<min)min=step;
		return ;
	}
	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(a[tx][ty]==0&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			DFS(tx,ty,step+1);
			book[tx][ty]=0;
		}
	}
	return ;
}
int main()
{
	int i,j,startx,starty;
	scanf("%d %d",&n,&m);
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			scanf("%d",&a[i][j]);
	scanf("%d %d %d %d",&startx,&starty,&p,&q);
	book[startx][starty]=1;
	DFS(startx,starty,0);
	printf("%d",min);
	return 0;
}

方法二(BFS):

#include <stdio.h>
struct note
{
	int x;
	int y;
	int s;
}; 
int main()
{
	struct note que[2501];
	int a[51][51]={0},book[51][51]={0};
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	int head=1,tail=1;
	int i,j,k,n,m,startx,starty,tx,ty,flag,p,q;
	scanf("%d %d",&n,&m);
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			scanf("%d",&a[i][j]);
	scanf("%d %d %d %d",&startx,&starty,&p,&q);
	que[tail].x=startx;
	que[tail].y=starty;
	que[tail].s=0;
	tail++;
	book[startx][starty]=1;
	flag=0;
	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||ty<1||tx>n||ty>m)
				continue;
			if(a[tx][ty]==0&&book[tx][ty]==0)
			{
				book[tx][ty]=1;
				que[tail].x=tx;
				que[tail].y=ty;	
				que[tail].s=que[head].s+1;
				tail++;
			}
			if(tx==p&&ty==q)
			{
				flag=1;
				break;
			}
		}
		if(flag==1)
			break;
		head++;
	}
	printf("%d",que[tail-1].s);//tail始终指向结尾的下一个位置 
	return 0;
}
发布了7 篇原创文章 · 获赞 2 · 访问量 155

猜你喜欢

转载自blog.csdn.net/PUZHANGYU/article/details/104602404
今日推荐