Representations of graphs: There are two standard ways to represent a graph G = (V, E): as a collection of adjacency lists(O(V+E)) or as an adjacency matrix(O(V^2)). The adjacency-list representation is usually preferred, because it provides a compact way to represent sparse graphs-those for which |E| is much less than |V|2. An adjacency-matrix representation may be preferred, however, when the graph is dense-|E| is close to |V|2-or when we need to be able to tell quickly if there is an edge connecting two given vertices. the simplicity of an adjacency matrix may make it preferable when graphs are reasonably small. Moreover, if the graph is unweighted, there is an additional advantage in storage for the adjacency-matrix representation. Rather than using one word of computer memory for each matrix entry, the adjacency matrix uses only one bit per entry. Breadth-first search: BFS(G, s) 1 for each vertex u ∈ V [G] - {s} 2 do color[u] ← WHITE 3 d[u] ← ∞ 4 π[u] ← NIL 5 color[s] ← GRAY 6 d[s] ← 0 7 π[s] ← NIL 8 Q ← Ø 9 ENQUEUE(Q, s) 10 while Q ≠ Ø 11 do u ← DEQUEUE(Q) 12 for each v ∈ Adj[u] 13 do if color[v] = WHITE 14 then color[v] ← GRAY 15 d[v] ← d[u] + 1 16 π[v] ← u 17 ENQUEUE(Q, v) 18 color[u] ← BLACK Required running time: O(V+E). Printing shortest path: PRINT-PATH(G, s, v) 1 if v = s 2 then print s 3 else if π[v] = NIL 4 then print "no path from" s "to" v "exists" 5 else PRINT-PATH(G, s, π[v]) 6 print v This procedure runs in time linear Depth-first search:
DFS(G) 1 for each vertex u ∈ V [G] 2 do color[u] ← WHITE 3 π[u] ← NIL 4 time ← 0 5 for each vertex u ∈ V [G] 6 do if color[u] = WHITE 7 then DFS-VISIT(u) DFS-VISIT(u) 1 color[u] ← GRAY ▹White vertex u has just been discovered. 2 time ← time +1 3 d[u] time 4 for each v ∈ Adj[u] ▹Explore edge(u, v). 5 do if color[v] = WHITE 6 then π[v] ← u 7 DFS-VISIT(v) 8 color[u] BLACK ▹ Blacken u; it is finished. 9 f [u] ▹ time ← time +1 Topological sort:
TOPOLOGICAL-SORT(G) 1 call DFS(G) to compute finishing times f[v] for each vertex v 2 as each vertex is finished, insert it onto the front of a linked list 3 return the linked list of vertices |