BFS——迷宫问题

在这里插入图片描述
在这里插入图片描述

#include "iostream"
#include "queue"
using namespace std;
struct Node
{
	int x, y;
	int step;
};
bool test(int x, int y, int m, int n,int a[][10],int visit[][10]);
void BFS(int x,int y,int a[][10],int visit[][10],int m,int n);
int main()
{
	int m, n;
	cout<<"请输入矩阵的行数m和列数n"<<endl;
	cin >> m >> n;
	char temp;
	int a[10][10];
	int visit[10][10] = { 0 };
	cout<<"请输入m行n列的矩阵"<<endl;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			cin >> temp;
			if (temp == '.')
				a[i][j] = 0;//表示平地可以走
			else if (temp == '*')
				a[i][j] = -1;//表示障碍物,不可以走
			else if (temp == 'S')//表示起点
				a[i][j] = 10;
			else if (temp== 'T')//表示终点
				a[i][j] = 100;
		}
	}
	for(int i=0;i<m;i++)
		for (int j = 0; j < n; j++)
		{
			if (a[i][j] == 10)
			{			
				BFS(i, j, a, visit, m, n);
			}
		}
	system("pause");
	return 0;
}
void BFS(int x, int y, int a[][10], int visit[][10],int m,int n)
{
	int X[4] = { 0,0,1,-1 };
	int Y[4] = { 1,-1,0,0 };
	queue<Node *> nodeQueue;
	Node *node=new Node();
	node->x = x;
	node->y = y;
	node->step = 0;
	nodeQueue.push(node);//将开始节点加入队列
	visit[x][y] = 1;
	while (!nodeQueue.empty())
	{
		Node *tnode;//指向队首节点
		tnode = nodeQueue.front();
		nodeQueue.pop();
		if (a[tnode->x][tnode->y]==100)//表明到达终点
		{
			cout << tnode->step<<endl;
			break;
		}
			for (int i = 0; i < 4; i++)
			{
				Node *tempnode = new Node();
				tempnode->x = tnode->x + X[i];
				tempnode->y = tnode->y + Y[i];
				tempnode->step = tnode->step + 1;
				if (test(tempnode->x, tempnode->y, m, n,a,visit))
				{
					visit[tempnode->x][tempnode->y] = 1;
					nodeQueue.push(tempnode);
				}
			

		}
		
	}
}
bool test(int x, int y,int m,int n,int a[][10],int visit[][10])//判断坐标是否合法
{
	if (x >= 0 && x < m&&y>=0 && y < n&&a[x][y]!=-1&&visit[x][y]==0)
		return true;//坐标合法
	else
		return false;//坐标越界
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值