最后一个点wa,求调,代码注释很清楚
查看原帖
最后一个点wa,求调,代码注释很清楚
1283833
_Persever_ance楼主2024/4/26 21:42
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<string>
using namespace std;
string dest = "123804765";
map<string, bool>hashp;
queue<pair<string,int>>q;
string pos;
int cnt;
int dx[4] = { -3,3,-1,1 };//上下左右
bool rightgo(int p0, int go,int d)
{
	if (go < 0 || go>8)	return false;
	if (p0 % 3 == 0 && d == -1)	return false;//特判左边界
	if (p0 % 3 == 2 && d == 1)	return false;//特判右边界
	return true;
}
int main()
{
	cin >> pos;
	q.push(make_pair(pos,0));//pos记录当前状态,cnt记录移动步数
	hashp[pos] = true;//记录是否走过
	while (!q.empty())
	{
		pos = q.front().first;
		cnt = q.front().second;
		int p0 = 0;
		while (pos[p0] != '0')	p0++;//0的位置
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int go = p0 + dx[i];
			char c;
			int flag = 0;//记录是否移动
			if (rightgo(p0,go,dx[i]))//移动坐标合法
			{
				flag = 1;
				c = pos[go];
				pos[go] = '0';
				pos[p0] = c;
				if (hashp[pos] != true)
				{
					hashp[pos] = true;
					q.push(make_pair(pos,cnt+1));
					if (pos == dest)
					{
						cout << cnt + 1;
						return 0;
					}
				}

			}
			if(flag==1)//复原
			{
				pos[go] = c;
				pos[p0] = '0';
			}
		}
	}
	return 0;
}
2024/4/26 21:42
加载中...