UVA - 10085 The most distant state

15 篇文章 0 订阅

题目大意:求所给图达到最远状态的时候,移动最少次的移动顺序。
解题思路:bfs+判重。定义一个结构体存放当前图,空白位置的坐标,移动次数即移动到该图的步骤。每改变一次就判断,然后放入队列。
依旧是参考别人题解的咸鱼。

#include<iostream> 
#include<cstdio>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
struct p {
    int ch[3][3];
    int x, y, step;
    string str;
};
p l, n;
bool vis[999999999];
queue<p> q;
int dx[]={-1, 1, 0, 0};
int dy[]={0, 0, -1, 1};
char dic[]={"UDLR"};
int ans, res[3][3];
string s;
int has(p tmp) {
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum = sum * 10 + tmp.ch[i][j];
    if (vis[sum]) return 0;
    vis[sum] = 1;
    return 1;
}
void bfs() {
    q.push(l);
    while (!q.empty()) {
        l = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int X = l.x + dx[i];
            int Y = l.y + dy[i];
            if (X < 0 || X > 2 || Y < 0 || Y > 2) continue;
            n = l;
            n.ch[l.x][l.y] = n.ch[X][Y];
            n.ch[X][Y] = 0;
            n.x = X;
            n.y = Y;
            n.str += dic[i];
            if (has(n)) {
                n.step += 1;
                if (n.step > ans) {
                    ans = n.step;
                    memcpy(res, n.ch, sizeof(res));
                    s = n.str;
                }
                q.push(n);
            }
        }
    }
}
int main() {
    int T;
    scanf("%d", &T);
    for (int t = 0; t < T; t++) {
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++) {
                scanf("%d", &l.ch[i][j]);
                if (l.ch[i][j] == 0) {
                    l.x = i;
                    l.y = j;
                }
            }
        l.step = 0;
        l.str = "";
        has(l);
        ans = 0;
        bfs();
        printf("Puzzle #%d\n", t+1);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++)
                printf("%d ", res[i][j]);
            printf("%d\n", res[i][2]);
        }
        cout << s << endl << endl;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值