UVa 10085 - The Most Distant State

传送门UVa 10085 - The Most Distant State


类似八数码的题目,只不过要求输出的是最长步数的状态。


如何确定这个状态?

队列的最后一个状态就是,不过也不一定,说不定前几个状态也可以。


如何输出路径?

开一个father数组,用于记录每一个状态的父状态,一个path数组,记录父状态到当前状态的移动方向。

用递归的方法到达初始状态,然后顺序输出。


#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 5000000;
const int dx[] = {-1, 1, 0, 0}; //上,下,左,右
const int dy[] = {0, 0, -1, 1};
const int HashSize = 10000003;
const char PathDir[5] = "UDLR"; //这里要和dir对应。

int head[HashSize], next[HashSize];
typedef int State[9];
State qu[MAXN], start, last;
int father[MAXN], path[MAXN], ans;

int TryToInsert(int s);
void BFS();
int Hash(State &s);
void PrintPath(int cur);

int main()
{
    //freopen("input.txt", "r", stdin);
    int T, i, j, cases = 1;
    scanf("%d", &T);
    while (T--)
    {
        for (i = 0; i < 9; i++)
            scanf("%d", &start[i]);
        BFS();
        printf("Puzzle #%d\n", cases++);
        for (i = 0; i < 3; i++)
            printf("%d %d %d\n", qu[ans][i * 3], qu[ans][i * 3 + 1], qu[ans][i * 3 + 2]);
        PrintPath(ans);
        printf("\n\n");
    }
    return 0;
}

void BFS()
{
    memset(head, 0, sizeof(head));
    memcpy(qu[0], start, sizeof(start));
    int front = 0, rear = 1;
    while (front < rear)
    {
        State &s = qu[front];
        //memcpy(last, s, sizeof(s));
        int z;
        for (z = 0; z < 9; z++)
            if (!s[z])
                break;
        int x = z / 3, y = z % 3;
        for (int d = 0; d < 4; d++)
        {
            int newx = x + dx[d];
            int newy = y + dy[d];
            int newz = newx * 3 + newy;
            if (newx >= 0 && newx < 3 && newy >= 0 && newy < 3)
            {
                State &t = qu[rear];
                memcpy(t, s, sizeof(s));
                t[newz] = s[z];
                t[z] = s[newz];
                if (TryToInsert(rear))
                {
                    father[rear] = front, path[rear] = d;   
                    rear++;
                }
            }
        }
        front++;
    }
    ans = rear - 1;
}

int TryToInsert(int s)
{
    int h = Hash(qu[s]);
    int u = head[h];
    while (u)
    {
        if (memcmp(qu[u], qu[s], sizeof(qu[s])) == 0)
            return 0;
        u = next[u];
    }
    next[s] = head[h];
    head[h] = s;
    return 1;
}

int Hash(State &s)
{
    int v = 0;
    for (int i = 0; i < 9; i++)
        v = v * 10 + s[i];
    return v % HashSize;
}

void PrintPath(int cur)
{
    if (cur != 0)
    {
        PrintPath(father[cur]);
        printf("%c", PathDir[path[cur]]);
    }
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值