八數碼 經典問題

闫柏军發表於2024-10-15

BFS!

#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int ans = 123456780;
const int P = 1e6 + 7;
vector<int>v[P + 5];
int n;
int fx[] = { 1,-1,0,0 };
int fy[] = { 0,0,1,-1 };
bool find(int x)
{
	int y = x % P;
	for (int i = 0; i < v[y].size(); i++)
	{
		if (v[y][i] == x)
			return true;
	}
	return false;
}
struct node
{
	int val;
	int step;
};
void bfs()
{
	queue<node>q;
	q.push({ n,0 });
	while (!q.empty())
	{
		node u = q.front();
		q.pop();
		if (u.val == ans)
		{
			cout << u.step;
			return;
		}
		//狀態轉移
		int a[5][5];
		int x = u.val;
		int kx, ky;
		for (int i = 3; i >= 1; i--)
		{
			for (int j = 3; j >= 1; j--)
			{
				a[i][j] = x % 10;
				x /= 10;
				if (a[i][j] == 0)kx = i, ky = j;
			}
		}
		int b[5][5];
		for (int i = 0; i < 4; i++)
		{
			memcpy(b, a, sizeof(a));
			int nx = kx + fx[i];
			int ny = ky + fy[i];
			if (nx > 3 || ny > 3 || nx < 1 || ny < 1)
				continue;
			swap(b[nx][ny], b[kx][ky]);
			int nownum=0;
			for (int i = 1; i <= 3; i++)
			{
				for (int j = 1; j <= 3; j++)
				{
					nownum *= 10;
					nownum += b[i][j];
				}
			}
			if (find(nownum))
				continue;
			v[nownum % P].push_back(nownum);
			q.push({ nownum,u.step + 1 });
		}
	}
	cout << -1;
	return;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	for (int i = 1; i <= 9; i++)
	{
		char x;
		cin >> x;
		n *= 10;
		if (x == 'x')
		{
			n += 0;
		}
		else
		{
			n += x - '0';
		}
	}
	v[n % P].push_back(n);
	bfs();
	return 0;
}

相關文章