八数码问题 poj 1077 康拓展开

题意:

八数码问题。


解析:

直接康拓展开state,化成一个类似hash的key。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1

using namespace std;
///        0! 1! 2! 3! 4!  5!   6!    7!    8!      9!
int fac[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int dir[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char index[] = "udlr";

bool vis[362880];
int cantor(int s[])
{
    int ret = 0;
    for (int i = 0; i < 9; i++)
    {
        int cnt = 0;
        for (int j = i + 1; j < 9; j++)
        {
            if (s[j] < s[i])
            {
                cnt++;
            }
        }
        ret += (cnt * fac[9 - i - 1]);
    }
    return ret + 1;
}

struct Node
{
    int state[9];
    int pos; //0的位置
    int key; //hash的key
    string path;
} now, Next;

string ansPath;

int goal = 46234; // 123456780 cantor展开对应的key
bool bfs()
{
	memset(vis, false, sizeof(vis));
	queue<Node> q;
	q.push(now);
	vis[now.key] = true;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.key == goal)
		{
			ansPath = now.path;
			return true;
		}
		int x = now.pos / 3;
		int y = now.pos % 3;
		for (int i = 0; i < 4; i++)
		{
			int nx = x + dir[i][0];
			int ny = y + dir[i][1];
			if (0 <= nx && nx < 3 && 0 <= ny && ny < 3)
			{
				Next = now;
				Next.pos = nx * 3 + ny;
				Next.state[now.pos] = Next.state[Next.pos];
				Next.state[Next.pos] = 0;
				Next.key = cantor(Next.state);
//				cout << now.key << endl;
				if (!vis[Next.key])
				{
					vis[Next.key] = true;
					Next.path = Next.path + index[i];
					q.push(Next);
				}
			}
		}
	}
	return false;
}

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL
    char c[2];
    while (~scanf("%s", c))
    {
        if (c[0] == 'x')
        {
            now.state[0] = 0;
            now.pos = 0;
        }
        else
        {
            now.state[0] = c[0] - '0';
        }
        for (int i = 1; i < 9; i++)
        {
            scanf("%s", c);
            if (c[0] == 'x')
            {
                now.state[i] = 0;
                now.pos = i;
            }
            else
            {
                now.state[i] = c[0] - '0';
            }
        }
        now.key = cantor(now.state);
        ansPath = "";
        if (bfs())
        	cout << ansPath << endl;
        else
        	printf("unsolvable\n");
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值