data-structure-experiments/13/bfs.c

72 lines
2.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// // Ref: P1605 迷宫
// 1、问题描述
// 迷宫实验是取自心理学的一个古典实验。在该实验中,把一只老鼠从一个无顶大盒子的门放入,在盒中设置了许多墙,对行进方向形成了多处阻挡。盒子仅有一个出口,在出口处放置一块奶酪,吸引老鼠在迷宫中寻找道路以到达出口。对同一只老鼠重复进行上述实验,一直到老鼠从入口到出口,而不走错一步。老鼠经多次试验终于得到它学习走迷宫的路线。
// 2、设计功能要求
// 迷宫由m行n列的二维数组设置0表示无障碍1表示有障碍。设入口为11出口为mn每次只能从一个无障碍单元移到周围四个方向上任一无障碍单元。编程实现对任意设定的迷宫求出一条从入口到出口的通路或得出没有通路的结论。
// 算法输入:代表迷宫入口的坐标
// 算法输出:穿过迷宫的结果。 算法要点:创建迷宫,试探法查找路。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int m, n;
int maze[105][105];
int vis[105][105];
typedef struct {
int x, y;
} Node;
Node *q[10005];
int head, tail;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
void push(Node *node) { q[tail++] = node; }
Node *front() { return q[head]; }
void pop() { head++; }
int empty() { return head == tail; }
int main() {
freopen("data.in", "r", stdin);
scanf("%d%d", &m, &n);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &maze[i][j]);
}
}
Node *start = (Node *)malloc(sizeof(Node));
start->x = 1;
start->y = 1;
push(start);
vis[1][1] = 1;
while (!empty()) {
Node *cur = front();
pop();
for (int i = 0; i < 4; i++) {
int nx = cur->x + dir[i][0];
int ny = cur->y + dir[i][1];
if (nx < 1 || nx > m || ny < 1 || ny > n) {
continue;
}
if (maze[nx][ny] == 0 && !vis[nx][ny]) {
Node *next = (Node *)malloc(sizeof(Node));
next->x = nx;
next->y = ny;
push(next);
vis[nx][ny] = 1;
}
}
}
if (vis[m][n]) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}