Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- #include <string.h>
- #include <limits.h>
- #include <malloc.h>
- #include <stdlib.h>
- int **maze;
- int m, n;
- int stepX[4] = { 1, 0, -1, 0 }, stepY[4] = { 0, 1, 0, -1 };
- typedef struct point {
- int x, y;
- }point;
- typedef struct queue {
- point value;
- queue *next;
- }queue;
- void pushBack(queue **head, point data) {
- queue *p = (queue*)malloc(sizeof(queue)), *t;
- if (*head == NULL) {
- p->value = data;
- p->next = NULL;
- *head = p;
- }
- else {
- p->value = data;
- p->next = NULL;
- t = *head;
- while (t->next) t = t->next;
- t->next = p;
- }
- }
- point pop(queue **head) {
- queue *p = (queue*)(malloc(sizeof(queue)));
- point value;
- p = (*head);
- *head = (*head)->next;
- value = p->value;
- free(p);
- return(value);
- }
- int check(point p) {
- return(((0 <= p.x) && (p.x < n)) && ((0 <= p.y) && (p.y < m)) && maze[p.y][p.x] != -2);
- }
- int bfs(point s) {
- int i;
- point pCrt, pNext;
- queue *head = NULL;
- pushBack(&head, s);
- while (head) {
- pCrt = pop(&head);
- for (i = 0; i < 4; i++) {
- pNext.x = pCrt.x + stepX[i];
- pNext.y = pCrt.y + stepY[i];
- if (check(pNext) && (maze[pNext.y][pNext.x] == -1 || maze[pNext.y][pNext.x] == -4)) {
- if (maze[pNext.y][pNext.x] != -4) {
- maze[pNext.y][pNext.x] = maze[pCrt.y][pCrt.x] + 1;
- pushBack(&head, pNext);
- }
- else return(maze[pCrt.y][pCrt.x] + 1);
- }
- }
- }
- return -1;
- } //обход в ширину
- int main() {
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- int i, j;
- char c;
- point s;
- scanf("%d %d", &m, &n);
- maze = (int**)malloc(m * sizeof(int*));
- for (i = 0; i < m; i++) {
- maze[i] = (int*)malloc(n * sizeof(int));
- for (j = 0; j < n; j++) {
- scanf("%c", &c);
- if (c == '\n') scanf("%c", &c);
- if (c == '.') maze[i][j] = -1;
- if (c == 'X') maze[i][j] = -2;
- if (c == 'S') {
- maze[i][j] = 0;
- s.y = i;
- s.x = j;
- }
- if (c == 'F') maze[i][j] = -4;
- }
- }
- printf("%d", bfs(s));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement