八数码问题

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map>
#include <math.h>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int LEN =362880;
struct node {
	int state[9];
	int dis;
};
int dir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int  visited[LEN] = { 0 };
int start[9];
int goal[9];
long int factory[] = { 1,1,2,6,24,120,720,5040,40320,362880 };
bool Cantor(int str[], int n) {
	long result = 0;
	for (int i = 0; i < n; i++) {
		int counted = 0;
		for (int j = i + 1; j < n; j++) {
			if (str[i] > str[j])
				++counted;
		}
		result += counted * factory[n - i - 1];
	}
	if (!visited[result]) {
		visited[result] = 1;
		return 1;
	}
	else return 0;
}
int bfs() {
	node head;
	memcpy(head.state,start, sizeof(head.state));
	head.dis= 0;
	queue<node>q;
	Cantor(head.state, 9);
	q.push(head);
	while (!q.empty()) {
		head = q.front();
		q.pop();
		int z;
		for (z = 0; z < 9; z++) {
		if (head.state[z]==0)break;
		}
		int x = z % 3;
		int y = z / 3;
		for (int i = 0; i < 4; i++) {
			int newx = x + dir[i][0];
			int newy = y + dir[i][1]; 
			int nz = newx + 3 * newy;
			if (newx >= 0 && newx < 3 && newy >= 0 && newy < 3) {
				node newnode;
				memcpy(&newnode, &head, sizeof(struct node));
				swap(newnode.state[z],newnode.state[nz]);
				newnode.dis++;
				if (memcmp(newnode.state, goal, sizeof(goal)) == 0)
					return newnode.dis;
				if (Cantor(newnode.state, 9))
					q.push(newnode);
			}
		}
	}
	return -1;
}
map<string, int>mp;
int main() {
	for (int i = 0; i < 9; i++)cin >> start[i];
	for (int i = 0; i < 9; i++)cin >> goal[i];
	int num = bfs();
	if (num != -1)cout << num << endl;
	else cout << "Impossible" << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值