美文网首页
有向无权图的最短路径

有向无权图的最短路径

作者: 摇摆苏丹 | 来源:发表于2023-06-27 16:23 被阅读0次
#define _CRT_SECURE_NO_WARNINGS
#include <unordered_map>
#include <vector>
#include <queue>
using namespace std;

struct Line
{
    bool visited = false;
    int length = 0;
    int from = -1;
};

int main()
{
    unordered_map<int, vector<int>> adj_list;
    FILE *fptr = fopen("input.txt", "r");

    int node_cnt;
    fscanf_s(fptr, "%d", &node_cnt);
    for (int i = 0; i < node_cnt; i++)
    {
        int node;
        fscanf_s(fptr, "%d", &node);
        vector<int> empty;
        adj_list[node] = empty;
    }

    int edge_cnt;
    fscanf_s(fptr, "%d", &edge_cnt);
    for (int i = 0; i < edge_cnt; i++)
    {
        int start;
        int end;
        fscanf_s(fptr, "%d%d", &start, &end);
        adj_list[start].push_back(end);
    }

    int start_idx;
    fscanf_s(fptr, "%d", &start_idx);

    vector<Line> table;
    for (int i = 0; i < node_cnt; i++)
    {
        Line line;
        table.push_back(line);
    }

    queue<int> q;
    q.push(start_idx);

    while (!q.empty())
    {
        int cur_idx = q.front();
        q.pop();

        if (table[cur_idx].visited)
        {
            continue;
        }
        table[cur_idx].visited = true;

        for (int idx : adj_list[cur_idx])
        {
            if (table[idx].from != -1)
            {
                continue;
            }
            table[idx].from = cur_idx;
            table[idx].length = table[cur_idx].length + 1;
            q.push(idx);
        }
    }

    return 0;
}
7
0
1
2
3
4
5
6
10
0   1
0   6
0   5
1   2
2   3
2   6
3   6
3   4
4   5
6   5
0

相关文章

  • 最短路径

    无权图的最短路径用BFS来求 O(|V|+|E|) 有向带权图两点之间的最短路径也包含了路径上其他顶点间的最短路径...

  • 最短路径问题

    无权图单源最短路径 有权图单源最短路径 有权图单源最短路径和无权图最短路径不一样,不能单从节点数来看,比如上图中,...

  • 《算法》笔记 12 - 最短路径

    加权有向图 数据结构加权有向边加权有向图最短路径 边的松弛 Dijkstra算法 地图或者导航系统是最短路径的典型...

  • java最短路径(jgrapht)

    基于jgrapht求最短路径的算法,有向图/无向图,加权图

  • 19-最短路径(Shortest Path)

    最短路径(Shortest Path) 最短路径是指两个顶点之间权值之和最小的路径(有向图,无向图均可,不能有负权...

  • 有向图和最短路径Dijkstra、Bellman-Ford、Fl

    本篇开始讨论关于有向图的算法,无向图是特殊的有向图。内容概要: 有向图的实现 最短路径经典算法实现 有向图的实现 ...

  • 第七讲-图(中)

    最短路径 问题分类:单源,多源 无权图的单源最短路径用bfs就可以解决。按照递增(非递减)的顺序找出从源到各个定点...

  • 无权最短路径

  • 静态寻路算法Dijkstra(python)

    算法介绍 迪科斯彻算法使用了广度优先搜索解决赋权有向图或者无向图的单源最短路径问题,算法最终得到一个最短路径树。该...

  • 【算法】单源最短路径

    概要 单源最短路径问题产生的基础是,带权重的有向图 最短路径的含义是,两个结点之间的路径中,总权重和最小的路径 单...

网友评论

      本文标题:有向无权图的最短路径

      本文链接:https://www.haomeiwen.com/subject/yujnydtx.html