【数据结构】用栈实现迷宫

前端之家收集整理的这篇文章主要介绍了【数据结构】用栈实现迷宫前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include <iostream>
  2. using namespace std;
  3. #define N 10
  4.  
  5. #include <stack>
  6.  
  7. struct pos
  8. {
  9. int _row;// 行
  10. int _col;// 列
  11. };
  12.  
  13. bool cheakstep(pos a)
  14. {
  15. if(a._col > -1||a._col < N-1||
  16. a._row > -1||a._row < N-1)
  17. {
  18. return true ;
  19. }
  20. return false ;
  21. }
  22.  
  23. bool IsPath(int arr[][N],pos nowloction,stack<pos>& s)
  24. {
  25.  
  26. pos tmp = nowloction;
  27. //入栈标记 栈不为空
  28. s.push (nowloction);
  29. arr[tmp._row][tmp._col] = 2;
  30.  
  31. while(!s.empty ())
  32. {
  33.  
  34. //shang
  35. pos now = s.top ();
  36.  
  37. if(now._row == N-1)
  38. {
  39. return true ;
  40. }
  41.  
  42. now._row -=1;
  43. if(cheakstep(now)==true && arr[now._row][now._col]==0)
  44. {
  45. s.push (now);
  46. arr[now._row ][now._col ]=2;
  47. continue;
  48. }
  49. //you
  50. now = s.top ();
  51. now._col +=1;
  52. if(cheakstep(now)==true && arr[now._row][now._col]==0)
  53. {
  54. s.push (now);
  55. arr[now._row ][now._col ]=2;
  56. continue;
  57. }
  58. //xia
  59. now = s.top ();
  60. now._row +=1;
  61. if(cheakstep(now)==true && arr[now._row][now._col]==0)
  62. {
  63. s.push (now);
  64. arr[now._row ][now._col ]=2;
  65. continue;
  66. }
  67.  
  68. //zuo
  69. now = s.top ();
  70. now._col -=1;
  71. if(cheakstep(now)==true && arr[now._row][now._col]==0)
  72. {
  73. s.push (now);
  74. arr[now._row ][now._col ]=2;
  75. continue;
  76. }
  77.  
  78. else
  79. {
  80. now = s.top ();
  81. arr[now._row ][now._col ] = 3;
  82. s.pop ();
  83.  
  84. }
  85. }
  86. return false ;
  87. }
  88.  
  89. int main()
  90. {
  91. //定义一个二维数组存放迷宫 1表示墙0表示路
  92. //定义一个栈存放路径
  93. //定义一个入口地址
  94. int arr[N][N]={
  95. 1,1,};
  96. pos entry = {2,0};
  97. stack<pos> path;
  98.  
  99.  
  100.  
  101. bool ret = IsPath(arr,entry,path);
  102.  
  103. if(ret == true )
  104. {
  105. cout<< "走出迷宫"<<endl;
  106. }
  107. else
  108. cout<< "没有走出迷宫"<<endl;
  109.  
  110.  
  111. for(int i=0;i<N;i++)
  112. {
  113. for(int j=0;j<N;j++)
  114. {
  115. cout<<arr[i][j];
  116. }
  117. cout<<endl;
  118. }
  119. cout<<endl;
  120. return 0;
  121. }

猜你在找的数据结构相关文章