原题链接:蓝桥杯历届试题-九宫重排
解题思路:
第一法,裸BFS,无任何数据结构进行嵌套
参考代码:
#include<bits/stdc++.h>
#define hh ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
const int maxn_3len=10000;
const int maxn=15;
const int map_maxn=1000;
const int dir[4][2]={1,0,-1,0,0,1,0,-1}; //方向向量
char beg[maxn],fin[maxn];
int beg_[maxn_3len][maxn][maxn]={0},fin_[maxn][maxn]={0};
//int vis[map_maxn][map_maxn];
struct state{
int x,y;
int step;
int cnt;
};
void print_map(int pos){
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<beg_[pos][i][j]<<' ';
}
cout<<endl;
}
cout<<endl;
}
void plan_map(int pos,int last){
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
beg_[pos][i][j]=beg_[last][i][j];
}
}
}
bool check_out(int pos){
bool flag=true;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(beg_[pos][i][j]!=fin_[i][j]){
flag=false;
}
}
}
return flag;
}
bool check_is(state s){
//if(!vis[s.x][s.y]&&s.x>=1&&s.x<=3&&s.y>=1&&s.y<=3){
if(s.x>=1&&s.x<=3&&s.y>=1&&s.y<=3){
return true;
}else{
return false;
}
}
int bfs(state st){
queue<state> q;
state now,next;
int pos=1; //用来表示beg_数组搜索的层数
q.push(st);
//vis[st.x][st.y]=1;
while(!q.empty()){
now=q.front();
q.pop();
//cout<<now.cnt<<endl;
//print_map(now.cnt);
if(check_out(now.cnt)){
return now.step;
}
for(int i=0;i<4;i++){
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.step=now.step+1;
//insert the new beg_ ,but how?????
next.cnt=pos++;
plan_map(next.cnt,now.cnt);
swap(beg_[next.cnt][next.x][next.y],beg_[next.cnt][now.x][now.y]);
if(check_is(next)){
q.push(next);
//vis[next.x][next.y]=1;
}
}
}
return -1;
}
int main(){
hh;
cin>>beg;
cin>>fin;
state start_point;
for(int i=1,pos=0;i<=3;i++){
for(int j=1;j<=3;j++){
if(beg[pos]!='.'){
beg_[0][i][j]=beg[pos]-'0';
} else{
beg_[0][i][j]=0;
start_point.x=i;
start_point.y=j;
start_point.step=0;
start_point.cnt=0;
}
if(fin[pos]!='.'){
fin_[i][j]=fin[pos++]-'0'; //第二次再自增
}else{
fin_[i][j]=0;
pos++;
}
}
}
cout<<bfs(start_point)<<endl;
return 0;
}
// 超时,炸内存,还 运行错误 67%准备再搞一发Hash进行嵌套。
0.0分
2 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复