八数码问题和状态图搜索

在一个3*3的棋盘上放置编号为1-8的8个方块,每占一格,另外还有一个空格与空格相邻的数字方块可以移动到空格里。

计算最少的移动步数

输入描述:

第一行输入初始棋局状态,第二行输入目标棋局状态

输入样例

1 2 3 0 8 4 7 6 5

1 0 3 8 2 4 7 6 5

输出样例:

2

康托展开:

定义Cantor()函数,该函数作用为判重

输入一个排列,即第一行的某个排列,计算出它的Cantor值,即第二行对应的数

康托展开式:X=a[n]*[n-1]!+a[n-1]*[]n-2!+......+a[1]*0!

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

using namespace std;

const int LEN = 362880;

struct node
{
	int state[9];
	int dis;
};

int dir[4][2] = {
	{-1,0},    //左
	{1,0},     //右
	{0,-1},    //上
	{0,1}      //下
};

int visited[LEN] = { 0 };  //标记每个状态,Contor()函数对它置数,并判重
int start[9];
int goal[9];     //目标

long int factory[] = { 1,1,2,6,24,120,720,5040,40320,362880 }; //1至8的阶乘

// 康托判重:X=a[n]*[n-1]!+a[n-1]*[]n-2!+......+a[1]*0!  
bool Cantor(int str[], int n) {
	long result = 0;
	for (int i = 0; i < n; i++) {
		int counted = 0;
		for (int j = i; j < n; j++){
			if (str[i] > str[j]) {     
				++counted;
			}
		}
		result += counted * factory[n - i - 1];   //排在第几位
	}
	//visited[]={0},当访问过,则标记为1
	if (!visited[result]) {
		visited[result] = 1;
		return 1;
	}
	else {
		return 0;   //未访问
	}
}

int bfs() {
	node head;
	//void memcpy(void *destin, void *source, unsibned n);
	//以source指向的地址为起点,将连续的n个字节数据,复制到以destin指向的地址为起点的内存中
	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();
		//大小比较,s1>s2 memcmp()>0; s1==s2 memcmp()=0; s1<s2 memcmp()<0
		if (memcmp(head.state, goal, sizeof(goal)) == 0) {
			return head.dis;
		}
		q.pop();
		int z;
		for (z =0; z < 9; z++){
			if (head.state[z] == 0) {
				break;
			}
		}
		//转换二维,3*3
		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 (Cantor(newnode.state, 9))
					q.push(newnode);
			}
		}
	}
	return -1;   //没找到
}


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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值