




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!





Graphs and matrices occur in a large variety of applications in computer science. In this chapter, we provide a brief introduction to these concepts, illustrating the two most commonly used data structures for representing graphs. Example problems are then examined, which illustrate both the benefits and the limitations of each of these representations.
A graph, such as the one shown at right, is composed of vertices (or nodes) and edges (or arcs). Either may carry additional information. If a graph is being used to model real-world objects, such as a roadmap, the value of a vertex might represent the name of a city, whereas an edge could represent a road from one city to another.
Graphs come in various forms. A graph is said to be directed if the edges have a designed beginning and ending point; otherwise, a graph is said to be undirected. We will restrict our discussion in this chapter to directed graphs. A second source of variation is the distinction between a weighted , or labeled, graph and an unweighted graph. In a weighted graph each edge is given a numerical value. For example, the value might represent the distance of a highway connecting two cities, or the cost of the airfare between two airports. An unweighted graph carries no such information. The graph shown above is both directed and weighted.
The two most common representations for a graph are an adjacency matrix and an edge list. An adjacency matrix represents a graph as a two-dimensional matrix. The vertices in the graph are numbered, and used as index values for the matrix. If the cities listed in the graph shown earlier are numbered in alphabetical order (Pendleton is 0, Pensacola is 1, and so on), then the resulting adjancency matrix is shown at left. Here a 1 value in position (i, j) indicates that there is a link between city i and j, and zero value indicates no such link. By convention, a node is always considered to be connected to itself.
The adjacency matrix representation has the disadvantage that it always requires O(v^2 ) space to store a matrix with v verticies, regardless of the number of edges. An alternative representation, the edge list, stores only the edges and is thus advantageous if the graph is relatively sparse. The basic idea is that each vertex will hold a set of adjacent edges:
Pendleton: {Pueblo, Phoenix} Pensacola: {Phoenix}
Peoria: {Pueblo, Pittsburgh} Phoenix: {Pueblo, Peoria, Pittsburgh} Pierre: {Pendleton} Pittsburgh: {Pensacola} Princeton: {Pittsburgh} Pueblo: {Pierre}
This edge list can easily be stored in a dictionary, where the index is the vertex (say, the city named), and the value is a list of adjacent cities. If the graph is weighted the list is replaced by a second dictionary, again indexed by verticies, which contains the weight for each edge.
The unweighted adjacency matrix representation of the graph given earlier can be defined in C as shown at right. We have used a symbolic constant to represent the size of the array.
There are a number of questions one could ask concerning any particular graph. One of the fundamental problems is the question of reachability. That is, what is the set of vertices that can be reached by starting from a particular vertex and moving only along the given arcs in the graph. Conversely, are there any vertices that cannot be reached by traveling in such a fashion.
There are two basic variations on this question. The single source question poses a specific initial starting vertex, and requests the set of vertices reachable from this vertex. The all pairs question seeks to generate this information simultaneously for all possible vertices. Of course, a solution to the all pairs question will answer the single source question as well. For this reason, we would expect that an algorithm that solves the all pairs problem will require at least as much effort as any algorithm for the single source problem.
The algorithm we will describe to illustrate the use of the adjacency matrix representation of graphs is known as Warshall's algorithm , after the computer scientist credited with its discovery. The heart of Warshall's algorithm is a triple of loops, which operate much like the loops in the classic algorithm for matrix multiplication. The key idea is that at each
int adjacency[N][N] = { { 1, 0, 0, 1, 0, 0, 0, 1}, { 0, 1, 0, 1, 0, 0, 0, 0}, { 0, 0, 1, 0, 0, 1, 0, 1}, { 0, 0, 1, 1, 0, 1, 0, 1}, { 1, 0, 0, 0, 1, 0, 0, 0}, { 0, 1, 0, 0, 0, 1, 0, 0}, { 0, 0, 0, 0, 0, 1, 1, 0}, { 0, 0, 0, 0, 1, 0, 0, 1} };
void warshall (int a[N][N]) { int i,j,k; for (k = 0; k < N; k++) { for (i = 0; i < N; i++) if (a[i][k] != 0) for (j = 0; j < N; j++) a[i][j] |= a[i][k] & a[k][j]; } }
If v is known to be reachable, discard Otherwise, add v to set of reachable vertices, then For all neighbors, vj , of v If vj is not is set of reachable vertices, add to stack
At each step of processing one node is removed from the stack. If it is a node that has not previously been reported as reachable, then the neighbors of the node are pushed on the stack. When the stack is finally empty, then all nodes that can be reached will have been investigated.
Question : Simulate the execution of this algorithm on the graph given earlier, using Pierre as your starting location. What city is not reachable from Pierre?
The type of search performed by this algorithm is known as a depth-first search. This mirrors a search that might be performed by an ant walking along the edges of the graph, and returning to a previous node when it discovers it has reached a vertex it has already seen. What is interesting about this algorithm is that if we replace the data structure, the stack, with an alternative, the queue, we get an entirely different type of search. Now, this is known as a breadth-first search. A breadth-first search looks at all possible paths at the same time. A mental image for this type of search would be to pour ink at the starting vertex, and see where it travels along all possible paths. In Worksheet 41 you will explore the differences between depth and breadth first search.
The weighted graph version of this algorithm is known as Dijkstra’s algorithm, again in honor of the computer scientist who first discovered it. Dijkstra’s algorithm uses a priority queue instead of a stack. It returns a dictionary of vertex/distance pairs. Because the priority queue orders values on shortest distance, it is guaranteed to find the shortest path. Dijkstra’s algorithm can be described as follows:
Dijkstra’s Shortest Path Algorithm : To find the shortest distance to vertices reachable from an initial vertex vs Initialize dictionary of reachable vertices with vs having cost zero, and add vs to a priority queue with distance zero While priority queue is not empty Get and remove (pop) vertex v with shortest distance from priority queue If v is known to be reachable, discard Otherwise, add v with given cost to dictionary of reachable vertices For all neighbors, vj , of v If vj is not is set of reachable vertices, combine cost of reaching v with cost to travel from v to vj , and add to priority queue
It is important that you add a vertex to the set of reachable nodes only when it is removed from the collection. As you will see when you complete worksheet 42, the cost when a vertex is first encountered in the inner loop may not be the shortest path possible. Because a priority queue is used, rather than the stack as in the earlier algorithm, a shorter
path that is subsequently uncovered will nevertheless be placed earlier in the queue, and thus will be the first to be removed from the queue.
As we noted at the start of this chapter, graphs and matrices appear in a wide variety of forms in computer science applications. In this section we will present a number of other classic graph algorithms.
Topological Sorting
Oftentimes a graph is used to represent a sequence of tasks, where a link between one task and the next indicates that the first must be completed before the second. When discussing university courses this is often termed a prerequisite chain. The following graph, for example, shows a typical table of courses and their prerequisites.
A topological order is a listing of vertices (in this case, courses), having the property that if b is a successor to a, then b occurs later in the ordering than a. For example, that you do not take any course without first taking its prerequisites. In effect, the topological ordering imposes a linear order on a graph. Of course, the topological order may not be unique, and many orderings may satisfy the sequence property.
A topological ordering can be found by placing all the vertices into a bag. The bag is then searched to find a vertex that has no successor. (As long as the graph has no cycles, such a vertex must exist). This will be the end of our sorted list. The vertex is removed, and the bag examined once more. The result will be a topological sort.
Greedy Algorithms
Many problems, particularly search problems, can be phrased in a form so that at each step there is a choice of many alternatives. The greedy method is a heuristic that provides guidance in how to construct a solution in these situations. The greedy technique says simply to take the next step that seems best from the current choices (that is, without resorting to any long-term planning). Dijkstra’s algorithm is a classic greedy algorithm. At each step, we simply select the move that gets us to a new destination with the least amount of work.
marked. Assume that a path from vertex I to j goes through vertex k, and uses no vertices numbered larger than k. Argue why at the end of the loop the position a[i][j] will be set to 1.
Wikipedia has a collection of links to various algorithms under an entry “List of Algorithms”. Algorithms described include most of those mentioned in this chapter, as well as many others.