[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;
}