What algorithm can I use to find the shortest path between specified node types in a graph?

后端 未结 8 2020
自闭症患者
自闭症患者 2021-02-14 12:19

This is the problem:

I have n points (p1, p2, p3, .. pn), each of them can connect to any other with a determined cost x.

Each point belongs to one of a set of p

8条回答
  •  轮回少年
    2021-02-14 12:23

    You can use the Floyd–Warshall algorithm. Here's the pseudocode given by WikiPedia:

    /* Assume a function edgeCost(i,j) which returns the cost of the edge from i to 
       (infinity if there is none).
       Also assume that n is the number of vertices and edgeCost(i,i)=0
    */
    
    int path[][];
    
    /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path
       from i to j using intermediate vertices (1..k-1).  Each path[i][j] is initialized to
       edgeCost(i,j) or infinity if there is no edge between i and j.
    */
    
    procedure FloydWarshall ()
        for k: = 1 to n
            for each (i,j) in {1,..,n}2
                path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );
    

    I had to write a program for an algorithms course about this same problem. This algorithm worked like a charm! Goodluck.

提交回复
热议问题