题目
跟着评论下的思路做的,反向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;
}