Graphs (4)
One solution of this problem is Dijkstra's algorithm. It works by constructing a shortest-path tree from the initial vertex to every other vertex in the graph. It is assumed that all weights are non-negative.
For every vertex, its (known) shortest distance to the starting vertex and its predecessor on that path are recorded.
At the beginning, the starting vertex is put into the tree, then other vertices are put into the tree one by one, according to their distances to the starting vertex. Each time a vertex is added into the tree, the shortest distances of the vertices outside the tree are adjusted, by checking if this new vertex provides a shorter path.
When the graph is implemented in an adjacency matrix, the worst-case running time of Dijkstra algorithm is O(|V|2).
Conceptual similarity with breadth first search
"Tree" defined in undirected graph is different from its definition in directed graph.
One spanning tree generation algorithm is similar to depth-first traversal, except that when a vertex is visited for the first time, the edge to it is included in G'. The path tree generated by Dijkstra algorithm for shortest distance is a spanning tree, too.
In a weighted graph, a minimum spanning tree has the one that has the smallest total weight among all spanning trees. If a graph has N vertices, its minimum spanning tree will have N-1 edges, though they don't have to be the ones with the lowest N-1 weights.
Prim's algorithm for minimum spanning tree is similar to Dijkstra algorithm, except that for every vertex to be processed, the remembered shortest distance is not from a fixed ("starting") vertex, but from any vertex that is already in the tree.
The algorithm starts with a vertex, and puts it into the minimum spanning tree to be generated. Then the following process is repeated until all nodes get into the tree: