Poj 1077 Eight!(BFS)
吃完晚饭,啃着tomato来poj上提交,结果不支持unordered_map,吐血啦,看来还是要用BFS+康托展开,还想再写一篇双向BFS的,对这道题算是圆满了*_*,但是要用G++提交,C++会报错我也不知道为嘛
#include<iostream> #include<cstring> #include<queue> using namespace std; const int N=362880; struct node{ int count,state[9]; char op[100]; }; int vis[N],start[9]; int goal[9]={1,2,3,4,5,6,7,8,0}; int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};//rlud long int factory[]={1,1,2,6,24,120,720,5040,40320,362880}; bool Cantor(int str[],int n){ long ans=0; for(int i=0;i<n;i++){ int cnt=0; for(int j=i+1;j<n;j++){ if(str[i]>str[j]) ++cnt; } ans+=cnt*factory[n-i-1]; } if(!vis[ans]){ vis[ans]=1; return 1; }else{ return 0; } } int BFS(){ memset(vis,0,sizeof(vis)); node head; queue<node> q; head.count=0; memcpy(head.state,start,sizeof(head.state)); q.push(head); while(!q.empty()){ head=q.front(); q.pop(); if(memcmp(head.state,goal,sizeof(goal))==0){ for(int i=0;i<head.count;i++) cout<<head.op[i]; return 1; } int z; for(z=0;z<9;z++){ if(head.state[z]==0) break; } int x=z%3; int y=z/3; for(int i=0;i<4;i++){ int dx=x+dir[i][0]; int dy=y+dir[i][1]; int dz=dx+3*dy; if(dx>=0&&dx<3&&dy>=0&&dy<3){ node tmp; memcpy(&tmp,&head,sizeof(struct node)); swap(tmp.state[z],tmp.state[dz]); if(i==0){//rlud tmp.op[tmp.count]='r'; tmp.count++; }else if(i==1){ tmp.op[tmp.count]='l'; tmp.count++; }else if(i==2){ tmp.op[tmp.count]='u'; tmp.count++; }else if(i==3){ tmp.op[tmp.count]='d'; tmp.count++; } if(Cantor(tmp.state,9)) q.push(tmp); } } } return -1; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); char ch; for(int i=0;i<9;i++){ cin>>ch; if(ch=='x') start[i]=0; else start[i]=ch-'0'; } int ans=BFS(); if(ans==-1) cout<<"unsolvable"<<endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了