求助!样例能过但提交全错 双向广搜
查看原帖
求助!样例能过但提交全错 双向广搜
1596929
heng_楼主2025/1/8 20:10

求助T.T


#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<unordered_map>
#define N 10

using namespace std;
int xx[8] = { 1,1,2,2,-1,-1,-2,-2 };
int yy[8] = { 2,-2,1,-1,2,-2,1,-1 };
string start;
string end1 = "111110111100*110000100000";
unordered_map<string, int> dist;
unordered_map<string, int> vis;
queue<string> s;



int IsSafe(int x, int y)
{
	return (x < 0 || y < 0 || x >= 5 || y >= 5) ? 0 : 1;
}

int BFS()
{
	int i;
	dist[start] = 0;
	dist[end1] = 0;
	vis[start] = 1;
	vis[end1] = 2;
	s.push(start);
	s.push(end1);
	while (!s.empty())
	{
		string t = s.front();
		s.pop();
		int distance = dist[t];
		int vist = vis[t];
		int a = t.find('*');
		int x1 = a / 5, y1 = a % 5;
		if (distance >= 8)
		{
			return -1;
		}


		for (i = 0;i < 8;i++)
		{
			int o = x1 + xx[i];
			int p = y1 + yy[i];
			if (!IsSafe(o, p))continue;

			int b = o * 5 + p;
			swap(t[a], t[b]);



			if (vis[t] + vist == 3)
			{
				if (distance + dist[t] + 1 <= 15)
					return distance + dist[t] + 1;
				return -1;
			}

			if (vis[t] > 0)
			{
				swap(t[a], t[b]);
				continue;
			}
			if (dist.count(t))
			{
				swap(t[a], t[b]);
				continue;
			}
			s.push(t);
			dist[t] = distance + 1;
			vis[t] = vist;
			swap(t[a], t[b]);



		}
	}

	return -1;
}

int main()
{

	int i, j;
	int t;
	scanf("%d", &t);
	getchar();
	while (t--)
	{
		char c;
		start.clear();

		for (i = 0;i < 5;i++) {
			for (j = 0;j < 5;j++) {
				scanf("%c", &c);
				start += c;
			}
			getchar();
		}
		if (start == end1)
		{
			printf("0\n");
			while (!s.empty()) s.pop();

			dist.clear();
			vis.clear();
			continue;
		}

		int ans = BFS();
		printf("%d\n", ans);
		while (!s.empty()) s.pop();

		dist.clear();
		vis.clear();
	}


	return 0;
}

2025/1/8 20:10
加载中...