挑战程序设计竞赛 【Aizu - 0121】Seven Puzzle

题目
跟着评论下的思路做的,反向bfs,以 01234567 为起点搜索出所有可能的步数,用map去保存。
头大。输入输出要特殊处理。

#include <iostream>
#include <cstring>
#include <queue>
#include <map>
#include <fstream>
using namespace std;

queue<string> que;
map<string, int> mp;
string card = "01234567";
int mov_dir[4] = {1, -1, 4, -4};

// ifstream IN("IN.txt", ios::in);
// ofstream OUT("OUT.txt", ios::out);

int bfs()
{
    que.push(card);
    mp[card] = 1;//初始化为 1,保证起点只被入队一次。

    while (que.size()) {
        string head = que.front();
        que.pop();
        string now;
        int idx = head.find('0');// 0 的下标
        for (int i = 0; i < 4; i++) {
            int now_idx = idx + mov_dir[i];// 将要交换的数字的下标
            now = head;
            if ( !(idx == 3 && now_idx == 4 || idx == 4 && now_idx == 3) && 
            (now_idx >= 0 && now_idx <= 7)) {//这种判断方法只有 第四和第五个数字是例外
            								//(数组下标为3 和 4)
                swap(now[idx], now[now_idx]);
                if (mp[now] == 0) {//map[key]的默认值位0,如果为0,说明该字符串没有入队过
                    mp[now] = mp[head] + 1;
                    que.push(now);
                }
            }
        }
    }

}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    bfs();
    string str = "01234567";
    while (1) {
        char ch;
        for (int i = 0; i < 8; i++){
            if (!(cin >> ch)) {
                return 0;
            }
            str[i] = ch;
        }
        cout << mp[str] - 1 << endl;//结果减1
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值