原文:

给定一个图和图中的一个源顶点,找到从源到给定图中所有顶点的最短路径。 我们已经在下面的帖子中讨论了 dijkstra 的最短路径算法。

上面讨论的实现只找到最短距离,但不打印路径。在这篇文章中,讨论了路径的打印。

for example, consider below graph and source as 0,
output should be
vertex           distance         path
0 -> 1          4        0 1 
0 -> 2          12        0 1 2 
0 -> 3          19        0 1 2 3 
0 -> 4          21        0 7 6 5 4 
0 -> 5          11        0 7 6 5 
0 -> 6          9        0 7 6 
0 -> 7          8        0 7 
0 -> 8          14        0 1 2 8

想法是创建一个单独的数组父[]。顶点 v 的父[v]值将 v 的父顶点存储在最短路径树中。根(或源顶点)的父级为-1。每当我们找到通过顶点 u 的较短路径时,我们就把 u 作为当前顶点的父顶点。

一旦我们构造了父数组,我们就可以使用下面的递归函数打印路径。

void printpath(int parent[], int j)
{
    // base case : if j is source
    if (parent[j]==-1)
        return;
    printpath(parent, parent[j]);
    printf("%d ", j);
}

下面是完整的实现

c

// c program for dijkstra's single 
// source shortest path algorithm.
// the program is for adjacency matrix
// representation of the graph.
#include 
#include 
// number of vertices 
// in the graph
#define v 9
// a utility function to find the 
// vertex with minimum distance
// value, from the set of vertices
// not yet included in shortest
// path tree
int mindistance(int dist[], 
                bool sptset[])
{
    // initialize min value
    int min = int_max, min_index;
    for (int v = 0; v < v; v  )
        if (sptset[v] == false &&
                   dist[v] <= min)
            min = dist[v], min_index = v;
    return min_index;
}
// function to print shortest
// path from source to j
// using parent array
void printpath(int parent[], int j)
{
    // base case : if j is source
    if (parent[j] == - 1)
        return;
    printpath(parent, parent[j]);
    printf("%d ", j);
}
// a utility function to print 
// the constructed distance
// array
int printsolution(int dist[], int n, 
                      int parent[])
{
    int src = 0;
    printf("vertex\t distance\tpath");
    for (int i = 1; i < v; i  )
    {
        printf("\n%d -> %d \t\t %d\t\t%d ",
                      src, i, dist[i], src);
        printpath(parent, i);
    }
}
// function that implements dijkstra's
// single source shortest path
// algorithm for a graph represented
// using adjacency matrix representation
void dijkstra(int graph[v][v], int src)
{
    // the output array. dist[i]
    // will hold the shortest
    // distance from src to i
    int dist[v]; 
    // sptset[i] will true if vertex
    // i is included / in shortest
    // path tree or shortest distance 
    // from src to i is finalized
    bool sptset[v];
    // parent array to store
    // shortest path tree
    int parent[v];
    // initialize all distances as 
    // infinite and stpset[] as false
    for (int i = 0; i < v; i  )
    {
        parent[0] = -1;
        dist[i] = int_max;
        sptset[i] = false;
    }
    // distance of source vertex 
    // from itself is always 0
    dist[src] = 0;
    // find shortest path
    // for all vertices
    for (int count = 0; count < v - 1; count  )
    {
        // pick the minimum distance
        // vertex from the set of
        // vertices not yet processed. 
        // u is always equal to src
        // in first iteration.
        int u = mindistance(dist, sptset);
        // mark the picked vertex 
        // as processed
        sptset[u] = true;
        // update dist value of the 
        // adjacent vertices of the
        // picked vertex.
        for (int v = 0; v < v; v  )
            // update dist[v] only if is
            // not in sptset, there is
            // an edge from u to v, and 
            // total weight of path from
            // src to v through u is smaller
            // than current value of
            // dist[v]
            if (!sptset[v] && graph[u][v] &&
                dist[u]   graph[u][v] < dist[v])
            {
                parent[v] = u;
                dist[v] = dist[u]   graph[u][v];
            } 
    }
    // print the constructed
    // distance array
    printsolution(dist, v, parent);
}
// driver code
int main()
{
    //  let us create the example
    // graph discussed above
    int graph[v][v] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
                       {4, 0, 8, 0, 0, 0, 0, 11, 0},
                        {0, 8, 0, 7, 0, 4, 0, 0, 2},
                        {0, 0, 7, 0, 9, 14, 0, 0, 0},
                        {0, 0, 0, 9, 0, 10, 0, 0, 0},
                        {0, 0, 4, 0, 10, 0, 2, 0, 0},
                        {0, 0, 0, 14, 0, 2, 0, 1, 6},
                        {8, 11, 0, 0, 0, 0, 1, 0, 7},
                        {0, 0, 2, 0, 0, 0, 6, 7, 0}
                    };
    dijkstra(graph, 0);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// a java program for dijkstra's
// single source shortest path
// algorithm. the program is for
// adjacency matrix representation
// of the graph.
class dijkstrasalgorithm {
    private static final int no_parent = -1;
    // function that implements dijkstra's
    // single source shortest path
    // algorithm for a graph represented
    // using adjacency matrix
    // representation
    private static void dijkstra(int[][] adjacencymatrix,
                                        int startvertex)
    {
        int nvertices = adjacencymatrix[0].length;
        // shortestdistances[i] will hold the
        // shortest distance from src to i
        int[] shortestdistances = new int[nvertices];
        // added[i] will true if vertex i is
        // included / in shortest path tree
        // or shortest distance from src to
        // i is finalized
        boolean[] added = new boolean[nvertices];
        // initialize all distances as
        // infinite and added[] as false
        for (int vertexindex = 0; vertexindex < nvertices;
                                            vertexindex  )
        {
            shortestdistances[vertexindex] = integer.max_value;
            added[vertexindex] = false;
        }
        // distance of source vertex from
        // itself is always 0
        shortestdistances[startvertex] = 0;
        // parent array to store shortest
        // path tree
        int[] parents = new int[nvertices];
        // the starting vertex does not
        // have a parent
        parents[startvertex] = no_parent;
        // find shortest path for all
        // vertices
        for (int i = 1; i < nvertices; i  )
        {
            // pick the minimum distance vertex
            // from the set of vertices not yet
            // processed. nearestvertex is
            // always equal to startnode in
            // first iteration.
            int nearestvertex = -1;
            int shortestdistance = integer.max_value;
            for (int vertexindex = 0;
                     vertexindex < nvertices;
                     vertexindex  )
            {
                if (!added[vertexindex] &&
                    shortestdistances[vertexindex] <
                    shortestdistance)
                {
                    nearestvertex = vertexindex;
                    shortestdistance = shortestdistances[vertexindex];
                }
            }
            // mark the picked vertex as
            // processed
            added[nearestvertex] = true;
            // update dist value of the
            // adjacent vertices of the
            // picked vertex.
            for (int vertexindex = 0;
                     vertexindex < nvertices;
                     vertexindex  )
            {
                int edgedistance = adjacencymatrix[nearestvertex][vertexindex];
                if (edgedistance > 0
                    && ((shortestdistance   edgedistance) <
                        shortestdistances[vertexindex]))
                {
                    parents[vertexindex] = nearestvertex;
                    shortestdistances[vertexindex] = shortestdistance  
                                                       edgedistance;
                }
            }
        }
        printsolution(startvertex, shortestdistances, parents);
    }
    // a utility function to print
    // the constructed distances
    // array and shortest paths
    private static void printsolution(int startvertex,
                                      int[] distances,
                                      int[] parents)
    {
        int nvertices = distances.length;
        system.out.print("vertex\t distance\tpath");
        for (int vertexindex = 0;
                 vertexindex < nvertices;
                 vertexindex  )
        {
            if (vertexindex != startvertex)
            {
                system.out.print("\n"   startvertex   " -> ");
                system.out.print(vertexindex   " \t\t ");
                system.out.print(distances[vertexindex]   "\t\t");
                printpath(vertexindex, parents);
            }
        }
    }
    // function to print shortest path
    // from source to currentvertex
    // using parents array
    private static void printpath(int currentvertex,
                                  int[] parents)
    {
        // base case : source node has
        // been processed
        if (currentvertex == no_parent)
        {
            return;
        }
        printpath(parents[currentvertex], parents);
        system.out.print(currentvertex   " ");
    }
        // driver code
    public static void main(string[] args)
    {
        int[][] adjacencymatrix = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                                    { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                                    { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                                    { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                                    { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                                    { 0, 0, 4, 0, 10, 0, 2, 0, 0 },
                                    { 0, 0, 0, 14, 0, 2, 0, 1, 6 },
                                    { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                                    { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
        dijkstra(adjacencymatrix, 0);
    }
}
// this code is contributed by harikrishnan rajan

计算机编程语言

# python program for dijkstra's
# single source shortest
# path algorithm. the program
# is for adjacency matrix
# representation of the graph
from collections import defaultdict
#class to represent a graph
class graph:
    # a utility function to find the
    # vertex with minimum dist value, from
    # the set of vertices still in queue
    def mindistance(self,dist,queue):
        # initialize min value and min_index as -1
        minimum = float("inf")
        min_index = -1
        # from the dist array,pick one which
        # has min value and is till in queue
        for i in range(len(dist)):
            if dist[i] < minimum and i in queue:
                minimum = dist[i]
                min_index = i
        return min_index
    # function to print shortest path
    # from source to j
    # using parent array
    def printpath(self, parent, j):
        #base case : if j is source
        if parent[j] == -1 :
            print j,
            return
        self.printpath(parent , parent[j])
        print j,
    # a utility function to print
    # the constructed distance
    # array
    def printsolution(self, dist, parent):
        src = 0
        print("vertex \t\tdistance from source\tpath")
        for i in range(1, len(dist)):
            print("\n%d --> %d \t\t%d \t\t\t\t\t" % (src, i, dist[i])),
            self.printpath(parent,i)
    '''function that implements dijkstra's single source shortest path
    algorithm for a graph represented using adjacency matrix
    representation'''
    def dijkstra(self, graph, src):
        row = len(graph)
        col = len(graph[0])
        # the output array. dist[i] will hold
        # the shortest distance from src to i
        # initialize all distances as infinite
        dist = [float("inf")] * row
        #parent array to store
        # shortest path tree
        parent = [-1] * row
        # distance of source vertex
        # from itself is always 0
        dist[src] = 0
        # add all vertices in queue
        queue = []
        for i in range(row):
            queue.append(i)
        #find shortest path for all vertices
        while queue:
            # pick the minimum dist vertex
            # from the set of vertices
            # still in queue
            u = self.mindistance(dist,queue)
            # remove min element    
            queue.remove(u)
            # update dist value and parent
            # index of the adjacent vertices of
            # the picked vertex. consider only
            # those vertices which are still in
            # queue
            for i in range(col):
                '''update dist[i] only if it is in queue, there is
                an edge from u to i, and total weight of path from
                src to i through u is smaller than current value of
                dist[i]'''
                if graph[u][i] and i in queue:
                    if dist[u]   graph[u][i] < dist[i]:
                        dist[i] = dist[u]   graph[u][i]
                        parent[i] = u
        # print the constructed distance array
        self.printsolution(dist,parent)
g= graph()
graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
        [4, 0, 8, 0, 0, 0, 0, 11, 0],
        [0, 8, 0, 7, 0, 4, 0, 0, 2],
        [0, 0, 7, 0, 9, 14, 0, 0, 0],
        [0, 0, 0, 9, 0, 10, 0, 0, 0],
        [0, 0, 4, 14, 10, 0, 2, 0, 0],
        [0, 0, 0, 0, 0, 2, 0, 1, 6],
        [8, 11, 0, 0, 0, 0, 1, 0, 7],
        [0, 0, 2, 0, 0, 0, 6, 7, 0]
        ]
# print the solution
g.dijkstra(graph,0)
# this code is contributed by neelam yadav

c

// c# program for dijkstra's
// single source shortest path
// algorithm. the program is for
// adjacency matrix representation
// of the graph.
using system;
public class dijkstrasalgorithm
{
    private static readonly int no_parent = -1;
    // function that implements dijkstra's
    // single source shortest path
    // algorithm for a graph represented
    // using adjacency matrix
    // representation
    private static void dijkstra(int[,] adjacencymatrix,
                                        int startvertex)
    {
        int nvertices = adjacencymatrix.getlength(0);
        // shortestdistances[i] will hold the
        // shortest distance from src to i
        int[] shortestdistances = new int[nvertices];
        // added[i] will true if vertex i is
        // included / in shortest path tree
        // or shortest distance from src to
        // i is finalized
        bool[] added = new bool[nvertices];
        // initialize all distances as
        // infinite and added[] as false
        for (int vertexindex = 0; vertexindex < nvertices;
                                            vertexindex  )
        {
            shortestdistances[vertexindex] = int.maxvalue;
            added[vertexindex] = false;
        }
        // distance of source vertex from
        // itself is always 0
        shortestdistances[startvertex] = 0;
        // parent array to store shortest
        // path tree
        int[] parents = new int[nvertices];
        // the starting vertex does not
        // have a parent
        parents[startvertex] = no_parent;
        // find shortest path for all
        // vertices
        for (int i = 1; i < nvertices; i  )
        {
            // pick the minimum distance vertex
            // from the set of vertices not yet
            // processed. nearestvertex is
            // always equal to startnode in
            // first iteration.
            int nearestvertex = -1;
            int shortestdistance = int.maxvalue;
            for (int vertexindex = 0;
                    vertexindex < nvertices;
                    vertexindex  )
            {
                if (!added[vertexindex] &&
                    shortestdistances[vertexindex] <
                    shortestdistance)
                {
                    nearestvertex = vertexindex;
                    shortestdistance = shortestdistances[vertexindex];
                }
            }
            // mark the picked vertex as
            // processed
            added[nearestvertex] = true;
            // update dist value of the
            // adjacent vertices of the
            // picked vertex.
            for (int vertexindex = 0;
                    vertexindex < nvertices;
                    vertexindex  )
            {
                int edgedistance = adjacencymatrix[nearestvertex,vertexindex];
                if (edgedistance > 0
                    && ((shortestdistance   edgedistance) <
                        shortestdistances[vertexindex]))
                {
                    parents[vertexindex] = nearestvertex;
                    shortestdistances[vertexindex] = shortestdistance  
                                                    edgedistance;
                }
            }
        }
        printsolution(startvertex, shortestdistances, parents);
    }
    // a utility function to print
    // the constructed distances
    // array and shortest paths
    private static void printsolution(int startvertex,
                                    int[] distances,
                                    int[] parents)
    {
        int nvertices = distances.length;
        console.write("vertex\t distance\tpath");
        for (int vertexindex = 0;
                vertexindex < nvertices;
                vertexindex  )
        {
            if (vertexindex != startvertex)
            {
                console.write("\n"   startvertex   " -> ");
                console.write(vertexindex   " \t\t ");
                console.write(distances[vertexindex]   "\t\t");
                printpath(vertexindex, parents);
            }
        }
    }
    // function to print shortest path
    // from source to currentvertex
    // using parents array
    private static void printpath(int currentvertex,
                                int[] parents)
    {
        // base case : source node has
        // been processed
        if (currentvertex == no_parent)
        {
            return;
        }
        printpath(parents[currentvertex], parents);
        console.write(currentvertex   " ");
    }
    // driver code
    public static void main(string[] args)
    {
        int[,] adjacencymatrix = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                                    { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                                    { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                                    { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                                    { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                                    { 0, 0, 4, 0, 10, 0, 2, 0, 0 },
                                    { 0, 0, 0, 14, 0, 2, 0, 1, 6 },
                                    { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                                    { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
        dijkstra(adjacencymatrix, 0);
    }
}
// this code has been contributed by 29ajaykumar

java 描述语言


输出:

vertex           distance         path
0 -> 1          4        0 1 
0 -> 2          12        0 1 2 
0 -> 3          19        0 1 2 3 
0 -> 4          21        0 7 6 5 4 
0 -> 5          11        0 7 6 5 
0 -> 6          9        0 7 6 
0 -> 7          8        0 7 
0 -> 8          14        0 1 2 8 

本文由阿迪蒂亚·戈尔供稿。如果你发现任何不正确的地方,请写评论,或者你想分享更多关于上面讨论的话题的信息