Advertisement
eddiehy

maze

Dec 6th, 2015
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //1表牆壁, 2表正確的路,3表回頭路
  4.  
  5. // 堆疊結構的宣告
  6. struct stack_node
  7. {
  8. int x;
  9. int y;
  10. struct stack_node *next;
  11. };
  12. typedef struct stack_node node;
  13.  
  14. node *path = NULL;
  15.  
  16. // 堆疊資料的存入
  17. node *push(node *stack, int x, int y)
  18. {
  19.  
  20. node *new_node;
  21. new_node = (node *)malloc(sizeof(node));
  22.  
  23. //判斷配置是否成功
  24.  
  25. if(new_node==NULL)
  26. {
  27. printf("記憶體配置失敗!\n");
  28. //exit(0);
  29. }
  30.  
  31. new_node->x = x;
  32. new_node->y = y;
  33. new_node->next = stack;
  34. stack = new_node;
  35.  
  36. return stack;
  37.  
  38. }
  39.  
  40.  
  41. //堆疊資料的取出
  42. node *pop(node *stack, int *x, int *y)
  43. {
  44. node *top;
  45.  
  46. if( stack != NULL ) //判斷堆疊是否為空的
  47. {
  48. top = stack;
  49. stack = stack->next;
  50. *x = top->x;
  51. *y = top->y;
  52. free(top);
  53. }
  54. else
  55. {
  56. *x = -1;
  57. *y = -1;
  58. }
  59. return stack;
  60. }
  61.  
  62.  
  63. void walk(int maze[][10], int x, int y)
  64. {
  65. while(1)
  66. {
  67. if(x==1 && y==1) // 是否為出口
  68. {
  69. path = push(path, x, y);
  70. maze[y][x] = 2; // 標示最後一點
  71. break;
  72. }
  73. maze[y][x] = 2; // 標示為走過的路
  74. if( maze[y-1][x] <= 0 ) // 往上方走
  75. {
  76. path = push(path, x, y);
  77. y--;
  78. }
  79. else if( maze[y+1][x] <= 0 ) // 往下方走
  80. {
  81. path = push(path, x, y);
  82. y++;
  83. }
  84. else if( maze[y][x-1] <= 0 ) // 往左方走
  85. {
  86. path = push(path, x, y);
  87. x--;
  88. }
  89. else if( maze[y][x+1] <= 0 ) // 往右方走
  90. {
  91. path = push(path, x, y);
  92. x++;
  93. }
  94. else // 無路可走 => 回朔
  95. {
  96. maze[y][x] = 3;
  97. path = pop(path, &x, &y); // 退回一步
  98. }
  99. }
  100. }
  101. void print_path(int x,int y)
  102. {
  103. if (path->next!=NULL)
  104. {
  105. path=path->next;
  106. print_path(path->x,path->y);
  107. }
  108. printf("[%2d,%2d]\n",x,y);
  109. }
  110.  
  111. // 主程式
  112. int main()
  113. {
  114. // 宣告
  115. int i, j;
  116.  
  117. // 輸入
  118. int maze[7][10] = // x=10, y=7
  119. {
  120. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  121. 1, 0, 1, 0, 1, 0, 0, 0, 0, 1,
  122. 1, 0, 1, 0, 1, 0, 1, 1, 0, 1,
  123. 1, 0, 1, 0, 1, 1, 1, 0, 0, 1,
  124. 1, 0, 1, 0, 0, 0, 0, 0, 1, 1,
  125. 1, 0, 0, 0, 1, 1, 1, 0, 0, 1,
  126. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  127. };
  128.  
  129. // 計算
  130. walk(maze, 8, 5);//8,5指迷宮入口
  131.  
  132. // 輸出
  133. printf("maze:\n");
  134. for(i=0; i<7; i++)
  135. {
  136. for(j=0; j<10; j++)
  137. printf("%d ", maze[i][j]);
  138. printf("\n");
  139. }
  140. printf("path:\n");
  141. print_path(path->x,path->y);
  142. // 結束
  143. system("pause");
  144. return 0;
  145. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement