八数码求解路径最短步数

#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>

using namespace std;
string s1;
int bfs(string start, string end)
{
	queue<string> q;
	unordered_map<string, int> d;
	unordered_map<string, string> q1;
	q.push(start);
	d[start] = 0;
	q1[start] = "";
	int dx[4] = { 1, -1, 0, 0 }, dy[4] = { 0, 0, 1, -1 };
	int we = 0;
	while (q.size())
	{

		auto t = q.front();      //取出栈顶数据
		q.pop();                 // 移除该数据
		int distance = d[t];
		string Q = q1[t];
		if (t == end)
		{
			s1 = Q;
			return distance;
		}
		int k = t.find('x');
		int x = k / 3, y = k % 3;

		for (int i = 0; i < 4; i++)                  //尝试向四周移动
		{
			int a = x + dx[i], b = y + dy[i];
			if (a >= 0 && a < 3 && b >= 0 && b < 3)  //判断移动后的步骤是否在范围内
			{
				swap(t[k], t[a * 3 + b]);
				if (!d.count(t))                     //记录如何移动
				{
					d[t] = distance + 1;
					if (i == 0)
					{
						q1[t] = Q + 's';
					}
					else if (i == 1)
					{
						q1[t] = Q + 'w';
					}
					else if (i == 2)
					{
						q1[t] = Q + 'd';
					}
					else if (i == 3)
					{
						q1[t] = Q + 'a';
					}
					q.push(t);
				}
				swap(t[k], t[a * 3 + b]);
			}
		}
	}
	return -1;
}
void Print(string start, string end)              // 逐步还原
{
	int a = s1.size();
	for (int i = 0; i < a; i++)
	{
		int k = start.find('x');

		if (s1[i] == 'w')
		{
			swap(start[k], start[k - 3]);
		}
		else if (s1[i] == 's')
		{
			swap(start[k], start[k + 3]);
		}
		else if (s1[i] == 'a')
		{
			swap(start[k], start[k - 1]);
		}
		else if (s1[i] == 'd')
		{
			swap(start[k], start[k + 1]);
		}
		cout << "第" << i + 1 << "步" << endl;
		cout << "--------" << endl;
		for (int i1 = 0; i1 < start.size(); i1++)
		{
			if (i1 == 0 || i1 == 3 || i1 == 6)
			{
				cout << "|" << start[i1] << " ";
			}
			else
			{
				cout << start[i1] << " ";
			}
			if ((i1 + 1) % 3 == 0)
			{
				cout << "|" << endl;
			}
		}
		cout << "--------";
		int wr = 9;
		for (int i2 = 0; i2 < 9; i2++)
		{
			if (start[i2] == end[i2])
			{
				wr--;
			}
		}
		cout << "差距: " << wr << endl;
		cout << endl;
	}
}
int main()
{
	cout << "实验人员:李昊" << endl;
	cout << "学号:2012020056" << endl;
	cout << "实验内容:八数码益智游戏" << endl;
	cout << "实验地点:基础实验中心网络实训室" << endl;
	string c, start;
	cout << "请输入起始状态" << endl;
	cout << "请用x表示空格" << endl;
	for (int i = 0; i < 9; i++)
	{
		cin >> c;
		start += c;
	}
	string end;
	cout << "请输入最终状态" << endl;
	for (int i = 0; i < 9; i++)
	{
		cin >> c;
		end += c;
	}
	int  a1 = bfs(start, end);
	if (a1 == -1)
	{

		cout << "未寻找到合适步骤" << endl;
	}
	else
	{
		cout << "共走 :" << a1 << "步" << endl;
		Print(start, end);
	}
	cout << "<<<<<<<<完成,请按下任意键结束>>>>>>>>" << endl;
	system("pause");
	return 0;
}




posted @ 2021-09-24 12:21  云鲸啊  阅读(98)  评论(3)    收藏  举报