鱼C论坛

 找回密码
 立即注册
查看: 2572|回复: 4

[已解决]C语言bfs寻找最短路径

[复制链接]
发表于 2023-4-18 18:19:46 | 显示全部楼层    本楼为最佳答案   
代码:
  1. #include <stdio.h>
  2. #include <stdbool.h>

  3. #define MAXN 100 // 最大节点数
  4. #define INF 0x3f3f3f3f // 无穷大

  5. int n, m; // n为节点数,m为边数
  6. int G[MAXN][MAXN]; // 邻接矩阵
  7. int dist[MAXN]; // 距离数组
  8. int pre[MAXN]; // 前驱节点数组
  9. bool visited[MAXN]; // 标记数组

  10. void bfs(int s) {
  11.     for (int i = 0; i < n; i++) {
  12.         dist[i] = INF; // 初始化距离数组
  13.         pre[i] = -1; // 初始化前驱节点数组
  14.         visited[i] = false; // 初始化标记数组
  15.     }
  16.     dist[s] = 0; // 起点距离为0
  17.     visited[s] = true; // 起点已经访问过
  18.     int q[MAXN], front = 0, rear = 0; // 队列及其指针
  19.     q[rear++] = s; // 起点入队
  20.     while (front < rear) { // 队列非空
  21.         int u = q[front++]; // 取出队首节点
  22.         for (int v = 0; v < n; v++) { // 遍历u的邻接点
  23.             if (G[u][v] != INF && !visited[v]) { // 如果v是u的邻接点且未访问过
  24.                 dist[v] = dist[u] + 1; // 更新v的距离
  25.                 pre[v] = u; // 设置v的前驱节点为u
  26.                 visited[v] = true; // 标记v已经访问过
  27.                 q[rear++] = v; // v入队
  28.             }
  29.         }
  30.     }
  31. }

  32. void print_path(int s, int t) {
  33.     if (s == t) { // 如果起点和终点相同,直接输出起点
  34.         printf("%d", s);
  35.         return;
  36.     }
  37.     int path[MAXN], top = 0; // 路径数组及其指针
  38.     for (int u = t; u != -1; u = pre[u]) { // 从终点往前遍历前驱节点
  39.         path[top++] = u; // 将节点加入路径数组
  40.     }
  41.     for (int i = top - 1; i >= 0; i--) { // 输出路径上的节点
  42.         printf("%d", path[i]);
  43.         if (i > 0) printf("->");
  44.     }
  45. }

  46. int main() {
  47.     scanf("%d%d", &n, &m);
  48.     for (int i = 0; i < n; i++) {
  49.         for (int j = 0; j < n; j++) {
  50.             G[i][j] = INF; // 初始化邻接矩阵
  51.         }
  52.     }
  53.     while (m--) {
  54.         int u, v;
  55.         scanf("%d%d", &u, &v);
  56.         G[u][v] = G[v][u] = 1; // 无向图,两个方向都要设置
  57.     }
  58.     int s, t;
  59.     scanf("%d%d", &s, &t);
  60.     bfs(s);
  61.     printf("Shortest path from %d to %d: ", s, t);
  62.     print_path(s, t);
  63.     printf("\n");
  64.     return 0;
  65. }
复制代码


                               
登录/注册后可看大图


                               
登录/注册后可看大图
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-9-27 02:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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