Depth First Search, Topological Sort, MST's




CS146

Chris Pollett

May 5, 2014

Outline

Introduction

Shortest paths

The following code prints the shortest path from vertex `s` to vertex `v` in a graph `G` assuming BFS has already computed a breadth-first tree. I.e., so each node `v` has its parent value `v.pi` set as described in the BFS algorithm.

PRINT-PATH(G, s, v)
1 if v == s
2    print s
3 elseif v.pi = NIL
4    print "no path from" s "to" v "exists"
5 else PRINT-PATH(G, s, v.pi)
6    print v

Depth First Search

Depth First Pseudo-code

As with breadth first search, we keep track of node color and predecessor `pi`. We also make use of a global variable time to timestamp a vertex `v` for when it was discovered `v.d` and when it was finished `v.f` (its adjacency list has been completely examined).

DFS(G)
1 for each vertex u in G.V //initialization
2    u.color = WHITE (recall white means unexplored)   
3    u.pi = nil
4 time = 0
5 for each vertex u in G.V
6    if u.color == WHITE
7        DFS-VISIT(G,u)


DFS-VISIT(G,u)
 1 time = time + 1
 2 u.d = time
 3 u.color = GRAY
 4 for each v in G.adj[u]
 5    if v.color == WHITE
 6        v.pi = u
 7        DFS-VISIT(G, v) // recursion means we're using a stack implicitly
 8 u.color = BLACK
 9 time = time + 1
10 u.f = time

DFS Example

Depth First Search Example

DFS Run-time

Quiz (Sec 5)

Which of the following statements is true?

  1. The run-time of the function LCS-LENGTH from last week only depended on the length of the longer sequence.
  2. The ACTIVITY-SELECTOR problem can be solved using a greedy algorithm.
  3. The breadth-first search algorithm from last week makes use of a stack.

Quiz (Sec 6)

Which of the following statements is true?

  1. The run-time of the function LCS-LENGTH from last week only depended on the length of the shorter sequence.
  2. The ACTIVITY-SELECTOR problem cannot be solved using Dynamic Programming.
  3. The breadth-first search algorithm from last week makes use of a queue.

Topological Sort

Topological Sort Example

Topological Sort Pseudo-code

We leverage our DFS code to give the following algorithm for topological sort:

TOPOLOGICAL-SORT(G)
1 call DFS(G) to compute finishing times v.f 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.

Minimum Spanning Trees

Minimum Spanning Tree Example

Growing a Spanning Tree

Pseudo-code for Generic MST

GENERIC-MST(G,w)
1 A = 0
2 while A does not form a spanning tree
3    find an edge (u,v) that is safe for A
4    A = A union {(u,v)}
5 return A

Next day we will explore how to find a safe edge.