摘要

题目链接 难度等级 完成状态 完成分数 最后编辑时间 失误原因(初次提交分数)
八数码难题 ★☆☆☆☆ 答案正确 100 2015-8-2 20:02:15 忘记判重(20)

题解

  • 由于数据量不大(容易知道最多9!=362880种状态),所以直接bfs找出最近的答案即可,注意判重(用map即可),不需要启发式搜索。

代码

显示/移除行号
  1. #include<cstdio>
  2. #include<string>
  3. #include<iostream>
  4. #include<queue>
  5. #include<climits>
  6. #include<map>
  7. using namespace std;
  8. //将字符串中的index 通过坐标加减 获取到新的位置//
  9. inline int getPoint(int p,int dx,int dy)
  10. {
  11. int x=p/3+1+dx,y=p%3+1+dy;
  12. return (x>0&&y>0&&x<=3&&y<=3)? 3*(x-1)+y-1 : -1;
  13. }
  14. //获取下一个index//
  15. const int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
  16. string next(string str,int d)
  17. {
  18. int zero=str.find('0'),got=getPoint(zero,dx[d],dy[d]);
  19. if(d==-1)return "";
  20. swap(str[zero],str[got]);
  21. return str;
  22. }
  23. map<string,int> Dis;
  24. queue<string> p;
  25. int main()
  26. {
  27. string from;
  28. cin>>from;
  29. p.push(from);
  30. //Bfs广搜//
  31. Dis[from]=0;
  32. while(!p.empty())//队列非空//
  33. {
  34. for(int i=0;i<=3;++i)//扩展下一个位置//
  35. {
  36. string nextStr=next(p.front(),i);
  37. //判重和无效(一开始忘记判重了- -不好意思)//
  38. if(nextStr==""||Dis.count(nextStr))continue;
  39. //更新目标点并入队//
  40. Dis[nextStr]=Dis[p.front()]+1;
  41. p.push(nextStr);
  42. //到达答案//
  43. if(nextStr=="123804765")
  44. {cout<<Dis["123804765"]<<endl;return 0;}
  45. }
  46. p.pop();
  47. }
  48. }

著作权声明[编辑]

关于[编辑]