



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




To motivate our first algorithm on graphs, consider the following problem. We are given an undirected graph G = (V, E) and a source vertex s ∈ V. The length of a path in a graph is the number of edges on the path. We would like to find the shortest path from s to each other vertex in the graph. The final result will be represented in the following way. For each vertex v ∈ V, we will store d[v] which is the distance (length of the shortest path) from s to v. Note that d[s] = 0.
We will also store a predecessor (or parent) pointer π[v] which is the first vertex along the shortest path if we walk from v backwards to s. We will set π[s] = Nil.
There is a simple brute-force strategy for computing shortest paths. We could simply start enumerating all simple paths starting at s, and keep track of the shortest path arriving at each vertex. However, there can be as many as n! simple paths in a graph. To see this, consider a fully connected graph shown in Figure 8.
There n choices for source node s, (n - 1) choices for destination node, (n - 2) for first hop (edge) in the path, (n - 3) for second, (n - 4) for third down to (n - (n - 1)) for last leg. This leads to n! simple paths. Clearly this is not feasible.
Here is a more efficient algorithm called the breadth-first search (BFS) Start with s and visit its adjacent nodes. Label them with distance 1. Now consider the neighbors of neighbors of s. These would be at distance 2. Now consider the neighbors of neighbors of
neighbors of s. These would be at distance 3. Repeat this until no more unvisited neighbors left to visit. The algorithm can be visualized as a wave front propagating outwards from s visiting the vertices in bands at ever increasing distances from s.
Figure 8.8: Source vertex for breadth-first-search (BFS)
Figure 8.9: Wave reaching distance 1 vertices during BFS
The generic graph traversal algorithm stores a set of candidate edges in some data structures we’ll call a “ bag ”. The only important properties of the “bag” are that we can put stuff into it and then later take stuff back out. Here is the generic traversal algorithm.
Notice that we are keeping edges in the bag instead of vertices. This is because we want to remember, whenever we visit v for the first time, which previously-visited vertex p put v into the bag. The vertex p is call the parent of v. The running time of the traversal algorithm depends on how the graph is represented and what data structure is used for the bag. But we can make a few general observations.
If we implement the bag by using a stack , we have depth-first search (DFS) or traversal.