[C++]Seven Puzzle
Seven Puzzle:
7数码问题。在2×4的棋盘上,摆有7个棋子,每个棋子上标有1至7的某一数字,不同棋子上标的数字不相同。棋盘上还有一个空格(用0表示),与空格相邻(上下左右)的棋子可以移到空格中,该棋子原先位置成为空格。给出一个初始状态(保证可以转移到最终状态),找出一种从初始状态转变成给定最终状态的移动棋子步数最少的移动步骤。
输入格式:
多组输入,每组8个数,表示初始状态前四个数为第一行从左到右,后四个数为第二行从左到右。
输出格式:
至少需要多少步可以从输入状态到达最终状态(0 1 2 3 4 5 6 7)
输入:
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
输出:
0
1
28
解题思路: 因为每个输入最终都会回到"01234567"这个状态,那就可以先打表,就是从"01234567"开始进行bfs,然后存储所有状态,输入比较即可。
不解的是Virtual Judge上如果不加if (!(cin >> a))return 0;
就会超时,加了就AC了…0.0
AC代码:
#include<iostream>
#include<map>;
#include<queue>
using namespace std;
string st = "01234567";
map<string, int> mp;
int ne[4] = {1, -1, 4, -4};
int bfs(){
queue<string> que;
que.push(st);
while(que.size()) {
string head = que.front();
que.pop();
int t = 0;
for(int i = 0; i<8; i++){
if(head[i] == '0'){
t = i;
break;
}
}
for(int i = 0; i<4; i++){
int nt = t + ne[i];
if(0<=nt && nt<8 && !(t==3 && i==0) && !(t==4 && i==1)){
string tail = head;
tail[t] = head[nt];
tail[nt] = head[t];
if(!mp[tail]){
mp[tail] = mp[head] + 1;
que.push(tail);
}
}
}
}
}
int main(){
bfs();
while(true){
mp[st] = 0;
string s = "";
for(int i = 0; i<8; i++){
int a;
if (!(cin >> a))return 0; //不加就超时???
s += (a + '0');
}
cout<<mp[s]<<endl;
}
return 0;
}