Advertisement
Guest User

bfs

a guest
May 21st, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4. #include <limits.h>
  5. #include <malloc.h>
  6. #include <stdlib.h>
  7.  
  8. int **maze;
  9. int m, n;
  10. int stepX[4] = { 1, 0, -1, 0 }, stepY[4] = { 0, 1, 0, -1 };
  11.  
  12. typedef struct point {
  13. int x, y;
  14. }point;
  15.  
  16. typedef struct queue {
  17. point value;
  18. queue *next;
  19. }queue;
  20.  
  21.  
  22. void pushBack(queue **head, point data) {
  23. queue *p = (queue*)malloc(sizeof(queue)), *t;
  24. if (*head == NULL) {
  25. p->value = data;
  26. p->next = NULL;
  27. *head = p;
  28. }
  29. else {
  30. p->value = data;
  31. p->next = NULL;
  32. t = *head;
  33. while (t->next) t = t->next;
  34. t->next = p;
  35. }
  36. }
  37.  
  38. point pop(queue **head) {
  39. queue *p = (queue*)(malloc(sizeof(queue)));
  40. point value;
  41. p = (*head);
  42. *head = (*head)->next;
  43. value = p->value;
  44. free(p);
  45. return(value);
  46. }
  47.  
  48. int check(point p) {
  49. return(((0 <= p.x) && (p.x < n)) && ((0 <= p.y) && (p.y < m)) && maze[p.y][p.x] != -2);
  50. }
  51.  
  52. int bfs(point s) {
  53. int i;
  54. point pCrt, pNext;
  55. queue *head = NULL;
  56. pushBack(&head, s);
  57. while (head) {
  58. pCrt = pop(&head);
  59. for (i = 0; i < 4; i++) {
  60. pNext.x = pCrt.x + stepX[i];
  61. pNext.y = pCrt.y + stepY[i];
  62. if (check(pNext) && (maze[pNext.y][pNext.x] == -1 || maze[pNext.y][pNext.x] == -4)) {
  63. if (maze[pNext.y][pNext.x] != -4) {
  64. maze[pNext.y][pNext.x] = maze[pCrt.y][pCrt.x] + 1;
  65. pushBack(&head, pNext);
  66. }
  67. else return(maze[pCrt.y][pCrt.x] + 1);
  68. }
  69. }
  70. }
  71. return -1;
  72. } //обход в ширину
  73.  
  74. int main() {
  75. freopen("input.txt", "r", stdin);
  76. freopen("output.txt", "w", stdout);
  77. int i, j;
  78. char c;
  79. point s;
  80. scanf("%d %d", &m, &n);
  81. maze = (int**)malloc(m * sizeof(int*));
  82. for (i = 0; i < m; i++) {
  83. maze[i] = (int*)malloc(n * sizeof(int));
  84. for (j = 0; j < n; j++) {
  85. scanf("%c", &c);
  86. if (c == '\n') scanf("%c", &c);
  87. if (c == '.') maze[i][j] = -1;
  88. if (c == 'X') maze[i][j] = -2;
  89. if (c == 'S') {
  90. maze[i][j] = 0;
  91. s.y = i;
  92. s.x = j;
  93. }
  94. if (c == 'F') maze[i][j] = -4;
  95. }
  96. }
  97. printf("%d", bfs(s));
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement