自己没想出来,看了其他人的思路
思路:用bfs和逆向处理
1、用bfs逆向推理出从终点到所有的起点所需的距离(用map表示)
2、用map进行查找
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include<iostream>
#include<map>
using namespace std;
#define MAX_A 10000
map <string,int> dp;//终点和从起点到达终点的距离
int direction[4] = {
1,-1,4,-4};//方向数组,分别表示向右,向左,向下,向上
//广度优先搜索,得dp数组
void bfs(){
string str;
str = "01234567";
dp[str] = 0;
queue <string> que;
que.push(str);
//当队列不为空,循环
while(que.size()){
//取出第一个
str = que.front();
que.pop();
//找到'0'所在的位置
int i;
int p;
for(i=0;i<8;i++){
if(str[i]-'0'==0){
p = i;
break;
}
}
//遍历四个方向
for(i=0;i<4;i++){
int k = p+direction[i];
if(k>=0&&k<8 &&!(p==3&&direction[i]==1)&&!(p==4&&direction[i]==-1)){
//在右上不能往右,在左下不能往左
//交换
string strx = str;
swap(strx[p],strx[k]);
if(dp.find(strx)==dp.end()){
dp[strx] = dp[str]+1;
que.push(strx);
}
}
}
}
}
int main(){
bfs();
string str;
while(getline(cin,str)){
str.erase(remove(str.begin(),str.end(),' '),str.end());
printf("%d\n",dp[str]);
}
return 0;
}