bfs 找步数最少的迷宫路径

在这里插入图片描述11步

#include<iostream>
#include<queue>
using namespace std;
const int maxn = 100;
struct node
{
	int x, y;
	int step;
}S,T,Node;
int n, m;
char map[maxn][maxn];
bool inqueue[maxn][maxn] = { false };
int x[4] = { 0,0,1,-1 };
int y[4] = { 1,-1,0,0 };
bool test(int x, int y)
{
	if (x >= n || x < 0 || y >= m || y < 0) return false;
	if (map[x][y] == '*') return false;
	if (inqueue[x][y]) return false;
	return true;
}
int bfs()
{
	queue<node>q;
	q.push(S);
	while (!q.empty())
	{
		node top = q.front();
		q.pop();
		if (top.x == T.x && top.y == T.y)
			return top.step;
		for (int i = 0; i < 4; i++)
		{
			int newx = top.x + x[i];
			int newy = top.y + y[i];
			if (test(newx, newy))
			{
				Node.x = newx, Node.y = newy;
				Node.step = top.step + 1;
				q.push(Node);
				inqueue[newx][newy] = true;
			}
		}
	}
	return -1;
}
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> map[i][j];
		}
	}
	cin >> S.x >> S.y >> T.x >> T.y;
	S.step = 0;
	cout << bfs();
	return 0;
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812021.html