当前位置:   article > 正文

C语言基础题:迷宫寻路(C语言版)

C语言基础题:迷宫寻路(C语言版)

1.题目描述


机器猫被困在一个矩形迷宫里。
迷宫可以视为一个n x m 矩阵,每个位置要么是空地,要么是墙。机器猫只能从一个空地走到其上、下、左、右的空地。
机器猫初始时位于(1,1)的位置,问能否走到(n,m)位置。

2.输入格式


第一行,两个正整数 n,m。
接下来几行,输入这个迷宫。每行输入一个长为 m 的字符串,#表示墙,. 表示空地。

3.输出格式


仅一行,一个字符串。如果机器猫能走到(n,m),则输出 Yes;否则输出 No 。

4.输入输出样例

1.输入:
  1. 3 5
  2. .##.#
  3. .#...
  4. ...#.
2.输出:
Yes

5.说明/提示


样例解释
路线如下:(1,1)→(2,1)→(3,1)→(3,2)→(3,3)→(2,3)→(2,4)→(2,5)→(3,5)

数据规模与约定
对于 100% 的数据,保证1< n,m < 100,(1,1)和(n,m)均为空地。

代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAXN 1000
  4. typedef struct {
  5. int x, y;
  6. } Point;
  7. int n, m;
  8. char maze[MAXN][MAXN + 1];
  9. int visited[MAXN][MAXN]; // 访问标记
  10. Point queue[MAXN * MAXN]; // 队列用于 BFS
  11. int front = 0, rear = 0;
  12. // 移动方向:上下左右
  13. int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
  14. void enqueue(Point p) {
  15. queue[rear++] = p;
  16. }
  17. Point dequeue() {
  18. return queue[front++];
  19. }
  20. int is_valid(int x, int y) {
  21. return (x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == '.' && !visited[x][y]);
  22. }
  23. int bfs() {
  24. enqueue((Point){0, 0}); // 从 (0,0) 开始
  25. visited[0][0] = 1; // 标记为已访问
  26. while (front < rear) {
  27. Point current = dequeue();
  28. // 如果到达终点 (n-1, m-1)
  29. if (current.x == n - 1 && current.y == m - 1) {
  30. return 1; // 可到达
  31. }
  32. // 检查四个方向
  33. for (int i = 0; i < 4; i++) {
  34. int new_x = current.x + dir[i][0];
  35. int new_y = current.y + dir[i][1];
  36. if (is_valid(new_x, new_y)) {
  37. visited[new_x][new_y] = 1; // 标记为已访问
  38. enqueue((Point){new_x, new_y}); // 入队
  39. }
  40. }
  41. }
  42. return 0; // 不可到达
  43. }
  44. int main() {
  45. scanf("%d %d", &n, &m);
  46. // 读取迷宫
  47. for (int i = 0; i < n; i++) {
  48. scanf("%s", maze[i]);
  49. }
  50. // 如果起点或终点是墙,直接输出 No
  51. if (maze[0][0] == '#' || maze[n-1][m-1] == '#') {
  52. printf("No\n");
  53. return 0;
  54. }
  55. // 执行 BFS
  56. if (bfs()) {
  57. printf("Yes\n");
  58. } else {
  59. printf("No\n");
  60. }
  61. return 0;
  62. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/927748
推荐阅读
相关标签
  

闽ICP备14008679号