数据结构:BFS求迷宫最短路径

bfs+队列求迷宫的最短路径, 类模板实现队列,A表示起点,B表示终点

#ifndef BFS1_H
#define BFS1_H
#include<stack>
#include<memory.h>
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
const int N=1e3+5;
const int MAXSIZE=100;

struct Node{
    int x, y;
    Node(int _x, int _y): x(_x), y(_y){};
	Node(){}
};
template<class T>
class Queue{
	private:
		T *base;
		int front;
		int rear;
	public:
		void InitQueue();
		bool IsEmpty();   //队空
		void EnQueue(T e);   //入队
		void DeQueue();   //出队
	    T GetHead();   //获得队首元素
};

template<class T>
void Queue<T>::InitQueue()
{
	base=new T[MAXSIZE];
	if(base == NULL ) cout<<"创建失败";
	front=0 ;
	rear=0;
}

template<class T>
bool Queue<T>::IsEmpty()
{
	return front==rear;
}

template<class T>
void Queue<T>::EnQueue(T e)
{
	//if((front+1)%MAXSIZE==rear) return false;
	rear=(rear+1)%MAXSIZE;
	base[rear]=e;
}

template<class T>
void Queue<T>::DeQueue()
{
	front=(front+1)%MAXSIZE;
}

template<class T>
T Queue<T>::GetHead()
{
	return base[rear];
}
#endif
#include"BFS1.h"
int vis[N][N];
char maze[N][N];
int n,m,s1,s2,e1,e2;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
bool flag;
//Queue<Node>Q;
Node pre[N][N];
void BFS();
int main()
{
//	Queue<Node> Q;
	int T;
	cin>>T;
	while(T--)
	{
		flag=false;
		cin>>n>>m;  //行 列
		for(int i=0; i<n;i++)
		{
			for(int j=0; j<m; j++)
			{
				cin>>maze[i][j];
				if(maze[i][j]=='A')   s1=i, s2=j;       //定义这里为起点
				if(maze[i][j]=='B')  e1=i, e2=j;   //定义这里为终点
			}
		}
		BFS();
		stack<Node> S;
		if(flag)
		{
			int prex=e1, prey=e2;
			while(1)
			{
			   S.push(Node(prex, prey));
			   if(prex==s1 && prey==s2) break; //到达起点
			   Node node=pre[prex][prey];
			   prex=node.x, prey=node.y;
			}
			while(!S.empty())
			{
				Node node=S.top();
			    S.pop();
				cout<<"("<<node.x<<','<<node.y<<')'<<endl;
			}
			cout<<endl;

		}
		else
		{
			cout<<"-1"<<'\n';
		}
	}
	return 0;
}

void BFS()
{
    Queue<Node>Q;
	Q.InitQueue();
	while(!Q.IsEmpty()) Q.DeQueue();
	memset(vis,0,sizeof(vis));
	Q.EnQueue(Node(s1,s2));
	vis[s1][s2]=1;
	while(!Q.IsEmpty())
	{
		Node node=Q.GetHead();
		Q.DeQueue();
		int x=node.x;
		int y=node.y;
		for(int d=0; d<4; d++)
		{
			int newx=x+dx[d];
			int newy=y+dy[d];
			if(newx>=0 && newy>=0 && newx<n && newy<m && maze[newx][newy]!='0' && vis[newx][newy]==0)
			{
				Q.EnQueue(Node(newx, newy));
				vis[newx][newy]=1;
			    pre[newx][newy]=Node(x,y);
				if(newx==e1 && newy==e2)
				{
					flag=true;
			 		break;   //到达终点
				}
			}
		}
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值