B14 BFS 八数码难题
#include <iostream> #include <algorithm> #include <queue> #include <unordered_map> using namespace std; char c; string str; unordered_map<string,int> d; queue<string> q; int dx[4]={-1, 0, 1, 0}; int dy[4]={0, 1, 0, -1}; int bfs(string str){ q.push(str); string end="123804765"; //目标状态 while(q.size()){ auto s=q.front(); q.pop(); if(s==end) return d[s]; //到达目标 int k=s.find('0'); int x=k/3, y=k%3; //下标位置转换 for(int i=0; i < 4; i++){ int a=x+dx[i], b=y+dy[i]; if(a<0||a>=3||b<0||b>=3)continue; int dis=d[s]; //记住步数 swap(s[k], s[a*3+b]); //交换 if(!d.count(s))d[s]=dis+1,q.push(s); swap(s[k], s[a*3+b]); //还原 } } } int main(){ for(int i=0; i<9; i++)cin>>c, str+=c; cout << bfs(str); return 0; }
#include <iostream> #include <algorithm> #include <queue> #include <unordered_map> using namespace std; string goal="123804765"; //目标状态 int dx[]={-1,0,1,0},dy[]={0,1,0,-1}; int bfs(string str){ unordered_map<string,int> d; queue<string> q; q.push(str); while(q.size()){ auto s=q.front(); q.pop(); if(s==goal) return d[s]; //边界 int k=s.find('0'); int x=k/3, y=k%3; //行列下标 for(int i=0; i < 4; i++){ int a=x+dx[i], b=y+dy[i]; if(a<0||a>=3||b<0||b>=3)continue; string t=s; swap(t[k],t[a*3+b]); //交换 if(!d.count(t)) d[t]=d[s]+1, q.push(t); } } } int main(){ char c; string str; for(int i=0; i<9; i++)cin>>c,str+=c; cout<<bfs(str); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!