问题描述:
在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;
}