鱼C论坛

 找回密码
 立即注册
查看: 2620|回复: 3

利用c语言实现用队列求解迷宫问题的最短路径

[复制链接]
发表于 2023-10-15 18:53:44 | 显示全部楼层
在C语言中,我们可以使用广度优先搜索(BFS)算法和队列数据结构来求解迷宫问题的最短路径。以下是一个简单的实现:

首先,我们需要定义一个队列和一个节点:

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. #define MAXSIZE 100

  4. typedef struct {
  5.     int x;
  6.     int y;
  7.     int step;
  8. } Node;

  9. typedef struct {
  10.     Node data[MAXSIZE];
  11.     int front;
  12.     int rear;
  13. } Queue;

  14. Queue* initQueue() {
  15.     Queue* q = (Queue*)malloc(sizeof(Queue));
  16.     q->front = 0;
  17.     q->rear = 0;
  18.     return q;
  19. }

  20. void enqueue(Queue* q, Node node) {
  21.     if ((q->rear + 1) % MAXSIZE == q->front) {
  22.         return;
  23.     }
  24.     q->data[q->rear] = node;
  25.     q->rear = (q->rear + 1) % MAXSIZE;
  26. }

  27. Node dequeue(Queue* q) {
  28.     if (q->front == q->rear) {
  29.         exit(0);
  30.     }
  31.     Node node = q->data[q->front];
  32.     q->front = (q->front + 1) % MAXSIZE;
  33.     return node;
  34. }

  35. int isEmpty(Queue* q) {
  36.     return q->front == q->rear;
  37. }
复制代码


然后,我们可以使用广度优先搜索(BFS)算法来找到迷宫的最短路径:

  1. #define N 5
  2. #define M 5

  3. int maze[N][M] = {
  4.     {0, 1, 0, 0, 0},
  5.     {0, 1, 0, 1, 0},
  6.     {0, 0, 0, 0, 0},
  7.     {0, 1, 1, 1, 1},
  8.     {0, 0, 0, 0, 0}
  9. };

  10. int visited[N][M] = {0};

  11. int direction[4][2] = {
  12.     {-1, 0}, // up
  13.     {1, 0},  // down
  14.     {0, -1}, // left
  15.     {0, 1}   // right
  16. };

  17. void BFS(int x, int y) {
  18.     Queue* q = initQueue();
  19.     Node start = {x, y, 0};
  20.     enqueue(q, start);
  21.     visited[x][y] = 1;

  22.     while (!isEmpty(q)) {
  23.         Node cur = dequeue(q);
  24.         if (cur.x == N - 1 && cur.y == M - 1) {
  25.             printf("The shortest path is %d steps.\
  26. ", cur.step);
  27.             return;
  28.         }

  29.         for (int i = 0; i < 4; i++) {
  30.             int newX = cur.x + direction[ i][0];
  31.             int newY = cur.y + direction[ i][1];

  32.             if (newX >= 0 && newX < N && newY >= 0 && newY < M && maze[newX][newY] == 0 && visited[newX][newY] == 0) {
  33.                 Node next = {newX, newY, cur.step + 1};
  34.                 enqueue(q, next);
  35.                 visited[newX][newY] = 1;
  36.             }
  37.         }
  38.     }

  39.     printf("No path found.\
  40. ");
  41. }

  42. int main() {
  43.     BFS(0, 0);
  44.     return 0;
  45. }
复制代码


在这个代码中,我们首先定义了一个迷宫和一个访问数组。然后,我们使用广度优先搜索(BFS)算法来找到迷宫的最短路径。我们从起点开始,然后探索每个方向,如果新的位置是可达的(即不是墙壁,并且没有被访问过),我们就将其添加到队列中,并更新步数和访问数组。当我们到达终点时,我们就找到了最短路径。如果队列为空,那么迷宫没有解决方案。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-5 04:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表