CIS 3223. Data Structures and Algorithms

Graphs (4)

 

6. Shortest path

A common problem in weighted graphs is to find the shortest paths from a given vertex to every other vertices. All the paths form a tree.

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

 

7. Minimum spanning trees

For a given connected undirected graph G, a "spanning tree" of G is a subgraph G' of G that is a tree and contains all vertices of G. In such a G', the number of edge is always one less than the number of vertices. A graph may have multiple spanning trees.

"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:

  1. Find all the edges from the newest vertex in the tree to other vertices that are not in the tree. Put these edges in the priority queue. If there are more than one edges to the same destination in the priority queue, only keep the shortest one.
  2. Pick the edge with the lowest weight in the priority queue, and add this edge and its destination vertex to the tree.
When the graph is implemented in an adjacency matrix, the worst-case running time of Prim's algorithm is also O(|V|2).