juinda

Untitled

Nov 29th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define LEN 9
  5. int side = 0,distant=0;
  6. int start_x = 1, start_y = 0; //设置起点
  7. int end_x = 8, end_y = 4; //设置终点
  8. int success = 0;
  9. int step(char *,int x, int y);
  10. void paint_maze(char *,int);
  11. void print_maze(char *);
  12. int main(int argc, char argv[])
  13. {
  14. scanf("%d", &side);
  15. char *maze=malloc(sizeof(char)*(side + 2)*(side + 2));
  16. for (int i = 0; i < side + 2; i++)
  17. for (int j = 0; j < side + 2; j++)
  18. *(maze+i*(side+2)+j) ='*';
  19. //printf("maze:\n"); //打印迷宫图,为方便查看,将数字换为图形打印
  20. paint_maze(maze,side);
  21. if (success==0)
  22. printf("\n沒有找到出口!\n");
  23. else if(success)print_maze(maze);
  24. system("pause");
  25. return 0;
  26. }
  27.  
  28. void paint_maze(int *maze,int board)
  29. {
  30. char ch;
  31. ch = getchar();
  32. for (int i = 1; i < board + 1; i++)
  33. {
  34. for (int j = 1; j < board + 1; j++)
  35. {
  36. *(maze + i*(board + 2) + j) = getchar();
  37. if (*(maze + i*(board + 2) + j) == 'S')
  38. {
  39. start_x = i;
  40. start_y = j;
  41. }
  42. else if (*(maze + i*(board + 2) + j) == 'T')
  43. {
  44. end_x = i;
  45. end_y = j;
  46. }
  47. }
  48. ch = getchar();
  49. }
  50. }
  51. int step(char *maze,int x, int y) //用递归算法求解路径
  52. {
  53. *(maze+(side+2)*x+y) ='1';
  54.  
  55. if (x == end_x && y == end_y)
  56. {
  57. success = 1; //打印函数放入递归中,每找到一条成功路径打印一次
  58. }
  59. if (success!=1&&y < (side+2) && *(maze+x*(side+2)+y+1) ==' ') { step(maze,x, y + 1); } //边界条件,避免溢出,感谢 @别把白天当黑夜 指正
  60. if (success != 1 && x < (side+2) && *(maze + (x+1)*(side + 2) + y) ==' ') { step(maze,x + 1, y); }
  61. if (success != 1 && y > 0 && *(maze + x*(side + 2) + y - 1) == ' ') { step(maze,x, y - 1); }
  62. if (success != 1 && x > 0 && *(maze + (x - 1)*(side + 2) + y) == ' ') { step(maze,x - 1, y); }
  63. if(success!=1)*(maze+(x*side+2)+y) =' ';
  64. }
  65.  
  66. void print_maze(char *maze)
  67. {
  68. int x, y;
  69.  
  70. for (x = 0; x < side+2; x++)
  71. {
  72. for (y = 0; y < side+2; y++)
  73. {
  74. if (*(maze+x*(side+2)+y) =='*')
  75. printf("■");
  76. else if (*(maze + x*(side + 2) + y) =='1')
  77. {
  78. printf("☆");
  79. distant++;
  80. }
  81. else printf("□");
  82. }
  83. printf("\n%d\n",distant);
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment