题目
题目描述
在一个
4
×
4
4\times 4
4×4 的棋盘上有 8 个黑棋和 8 个白棋,当且仅当两个格子有公共边,这两个格子上的棋是相邻的。移动棋子的规则是交换相邻两个棋子。
给出一个初始棋盘和一个最终棋盘,请找出一个最短的移动序列使初始棋盘变为最终棋盘。
输入格式
前四行,每行 4 个数字(1 或者 0),描述了初始棋盘;
接着是一个空行;
第六到第九行,每行 4 个数字(1 或者 0),描述了最终棋盘。
输出格式
输出文件的第一行是一个整数 n,表示最少的移动步数。
样例
输入
1111
0000
1110
0010
1010
0101
1010
0101
输出
4
代码详解
ACcode
#include<bits/stdc++.h>
using namespace std;
int dx[4]={1,0,0,-1};
int dy[4]={0,-1,1,0};
struct node{
int step;
int z[5][5];
}fir,fin;
queue<node> q;
unordered_set<int> ss;
int cod(node);
bool vis(node);
void bfs();
int main()
{
char ch;
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
cin>>ch;
fir.z[i][j]=ch-'0';
}
}
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
cin>>ch;
fin.z[i][j]=ch-'0';
}
}
fir.step=0;
q.push(fir);
ss.emplace(cod(fir));
bfs();
return 0;
}
int cod(node t){
int s=0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
s*=10;
s+=t.z[i][j];
}
}
return s;
}
bool vis(node t){
int tmp=cod(t);
if(!ss.count(tmp)){
ss.emplace(tmp);
return true;
}
return false;
}
void bfs(){
while(!q.empty()){
node now=q.front();
q.pop();
if(cod(now)==cod(fin)){
cout<<now.step;
return;
}
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
for(int k=0;k<4;k++){
int xx=i+dx[k],yy=j+dy[k];
if(xx>=1&&xx<=4&&yy>=1&&yy<=4){
node fut=now;
swap(fut.z[i][j],fut.z[xx][yy]);
if(vis(fut)){
fut.step=now.step+1;
q.push(fut);
}
}
}
}
}
}
}
主函数
int main()
{
char ch;
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
cin>>ch;
fir.z[i][j]=ch-'0';
}
}
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
cin>>ch;
fin.z[i][j]=ch-'0';
}
}
fir.step=0;
q.push(fir);
ss.emplace(cod(fir));
bfs();
return 0;
}
在输入的时候把字符类型转换成整型
初始化一开始的步数为0
让ss记录一下fir的状态
cod函数
int cod(node t){
int s=0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
s*=10;
s+=t.z[i][j];
}
}
return s;
}
把这个棋盘转换成10进制
vis函数
bool vis(node t){
int tmp=cod(t);
if(!ss.count(tmp)){//如果从未出现过
ss.emplace(tmp);//记录一下
return true;
}
return false;
}
bfs
void bfs(){
while(!q.empty()){
node now=q.front();//取队头
q.pop();
if(cod(now)==cod(fin)){//若到达结束状态
cout<<now.step;
return;
}
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){//ij遍历每个格子
for(int k=0;k<4;k++){//与上下左右哪个格子交换
int xx=i+dx[k],yy=j+dy[k];
if(xx>=1&&xx<=4&&yy>=1&&yy<=4){//如果在范围内
node fut=now;
swap(fut.z[i][j],fut.z[xx][yy]);//交换一下
if(vis(fut)){//满足条件
fut.step=now.step+1;//步数++
q.push(fut);
}
}
}
}
}
}
}
end
经典bfs,相信读者能够看明白大部分的代码,笔者在这不做赘述