迷宫走法(基于BFS)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*
测试数据
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3

7
*/
struct node
{
	int x;
	int y;
	int f;
	int s;
};
int main(){
	int n,m,tx,ty,px,py,startx,starty;
	int a[51][51]={0},book[51][51]={0};
	int next[4][2]={
   
   {0,1},{1,0},{0,-1},{-1,0}};
	scanf("%d%d",&n,&m);
	for(int i = 1;i<=n;i++){
		for(int j = 1;j<=m;j++)
		scanf("%d",&a[i][j]);
	}
	scanf("%d %d %d %d",&startx,&starty,&px,&py);
	book[startx][starty]=1;
	struct node que[2501];
	int head,tail;	
	head = 1;
	tail = 1;
	que[tail].x=startx;
	que[tail].y=starty;
	que[tail].f=0;
	que[tail].s=0;
	tail++;
	int flag = 0 ;
	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){
				book[tx][ty]=1;
				que[tail].x=tx;
				que[tail].y=ty;
				que[tail].f=head;
				que[tail].s=que[head].s+1;
				tail++;
			}
			if(tx==px && ty==py){
				flag =1;
				break;
			}
		}
		//注意这两条语句要放到for循环的外面  
		//因为for循环相当于将某一个点进行一次全部寻找 并加入队列中
		//当将其全部结点都加入以后 我们就可以进行head++ 寻找下一个结点的拓展 
		if(flag==1)
			break; 
		head++;
	}
	printf("%d\n",que[tail-1].s);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_49019274/article/details/114858051