問題描述:
在3×3的棋盤上,擺有八個棋子,每個棋子上標有1至8的某一數字。棋盤中留有一個空格,空格用0來表示。空格周圍的棋子可以移到空格中。要求解的問題是:給出一種初始佈局(初始狀態)和目標佈局123804765,找到一種最少步驟的移動方法,實現從初始佈局到目標佈局的轉變。
輸入
一行,9個數,表示方陣的初始狀態
輸出
一行,一個整數,表示最少步數。若在5000步內無解,則輸出-1.
樣例輸入
123840765
樣例輸出
1
提示
解釋:樣例中123840765是3*3的方陣
1 2 3
8 4 0
7 6 5
目標方陣是:
1 2 3
8 0 4
7 6 5
從學習寬搜的那年開始,每年都要寫一次,這次寫了個超簡單版的,主要是C++裏的STL幫了大忙。詳細看下面代碼,我想,懂BFS框架的小白應該也能輕鬆駕馭它了吧。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 362800+16;
string endS = "123804765";
struct node{
string s;
int pos,step;//s表示狀態,pos表示0所在的位置,step步數。
};
queue<node>q;
map<string ,bool> mp;
int changeId[9][4] = {
{-1,-1,3,1},{-1,0,4,2},{-1,1,5,-1},
{0,-1,6,4},{1,3,7,5},{2,4,8,-1},
{3,-1,-1,7},{4,6,-1,8},{5,7,-1,-1}
};//0出現在0->8的位置後該和哪些位置交換
void swapS(string &s,int pos ,int topos){
char t ;
t = s[pos],s[pos] = s[topos] , s[topos] = t;
}
int bfs(string s,int pos0){
q.push((node){s,pos0,0});
mp[s] = true;
while(!q.empty()){
node head = q.front();
q.pop();
int pos = head.pos;
string cur = head.s;
if(cur == endS) return head.step;
if(head.step> 5000) return -1;
for(int i = 0; i< 4; i++){ //四個方向上交換
string newCur = cur;
int topos = changeId[pos][i]; //因爲將0在每個位置上可以交換的位置進行了打表,減少了程序代碼量。
if(topos != -1){
swapS(newCur,pos,topos);
if(!mp[newCur]){ //新產生的狀態如果沒有出現過,則入隊列標狀態。
q.push((node){newCur,topos,head.step+1});
mp[newCur] = true;
}
}
}
}
return -1;
}
int main(){
int pos0,ans = 0;
string starts;
cin >> starts;
//找0所在的位置
pos0 = starts.find('0');
if(starts != endS) ans = bfs(starts,pos0);
cout << ans;
return 0;
}