八方块移动游戏要求从一个含 88 个数字(用 1-81−8 表示)的方块以及一个空格方块(用 00表示)的 3 \times 33×3 矩阵的起始状态开始,不断移动该空格方块以使其和相邻的方块互换,直至达到所定义的目标状态。空格方块在中间位置时有上、下、左、右 44 个方向可移动,在四个角落上有 22 个方向可移动,在其他位置上有 33个方向可移动。例如,假设一个 3\times 33×3 矩阵的初始状态为:
8 0 3
2 1 4
7 6 5
目标状态为:
1 2 3
8 0 4
7 6 5
则一个合法的移动路径为:
8 0 3 > 8 1 3 > 8 1 3 > 0 1 3 > 1 0 3 > 1 2 3
2 1 4 > 2 0 4 > 0 2 4 > 8 2 4 > 8 2 4 > 8 0 4
7 6 5 > 7 6 5 > 7 6 5 > 7 6 5 > 7 6 5 > 7 6 5
另外,在所有可能的从初始状态到目标状态的移动路径中,步数最少的路径被称为最短路径;在上面的例子中,最短路径为 55 。如果不存在从初试状态到目标状态的任何路径,则称该组状态无解。 请设计有效的(细节请见评分规则)算法找到从八方块的某初试状态到某目标状态的所有可能路径中的最短路径。
输入格式
程序需读入初始状态和目标状态,这两个状态都由 99 个数字组成( 00 表示空格, 1-81−8 表示 88 个数字方块),每行 33 个数字,数字之间用空格隔开。
输出格式
如果输入数据有解,输出一个表示最短路径的非负的整数;如果输入数据无解,输出 -1
−1
#include <iostream>
#include <queue>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
struct node{
int x,y;
int G[5][5];
int step;
};
node soldier;//肩负着插队的使命
node ans;
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
string loading=" ";
map<string,bool> vis;
string series(node temp){
string character=" ";
character=" ";
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
character+=char('0'+temp.G[i][j]);
return character;
}
int bfs(){
queue<node> q;
q.push(soldier);
while(!q.empty()){
node charge=q.front();
q.pop();
for(int i=0;i<4;i++){
node temp=charge;
temp.x=charge.x+dirx[i];
temp.y=charge.y+diry[i];
temp.step=charge.step+1;
if(temp.x>=0&&temp.x<3&&temp.y>=0&&temp.y<3){
swap(temp.G[charge.x][charge.y],temp.G[temp.x][temp.y]);
string t=series(temp);
if(loading==t)return temp.step;
if (vis.find(t) == vis.end()) {
vis[t] = true;
q.push(temp);
}
}
}
}
return -1;
}
int main(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cin>>soldier.G[i][j];
if(soldier.G[i][j]==0){
soldier.x=i;
soldier.y=j;
soldier.G[i][j]=9;
}
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cin>>ans.G[i][j];
if(ans.G[i][j]==0)ans.G[i][j]=9;
}
}
loading=series(ans);
cout<<bfs()<<endl;
return 0;
}