06 Graphs
06 Graphs
1
Finding Cycles Post-Order DFS
Cycle_test_DFS(vertex u, p) //p is parent, needed only for undirected case postorder_DFS(vertex u, ref int nextnum)
u.marked = true; u.onpath = true;
//perform required operation
u.marked = true
for all neighbors v of u for all neighbors v of u
if v.onpath and (graph is directed or v != p) if not v.marked
announce cycle postorder_DFS(v, nextnum)
halt
if not v.marked u.ponum = nextnum++
cycle_test_DFS(v,u) postorder_main
u.onpath = false for all nodes u
main
for all nodes u
u.marked = false
u.marked = false; u.onpath = false int nextnum = 1
for all nodes u for all nodes u
if not u.marked if not u.marked
cycle_test_DFS(u, nil)
announce no cycle postorder_DFS(u, nextnum)
2
Dijkstra’s Algorithm Dijkstra’s Algorithm
DijkstraSSSP(vertex u)
• Greedy algorithm for the SSSP problem vertex_set unsettled = V – {u}
for all nodes v //O(N)
• Abstractions used v.cost = infinity
for all neighbors v of u //O(N)
– Adjacency lists for neighbors of a node and v.cost = weight(u,v)
the cost of edges while not unsettled.empty() //O(N)
find v in unsettled s.t. v.cost is minimal //O(NlogN) if partially ordered tree
– Priority queue of nodes (“unsettled” nodes) for unsettled -= {v}
for all neighbors w of v O(E)
which the cheapest path has not yet been if v.cost + weight(v,w) < w.cost
identified //shorter path from u to w through v
w.cost = v.cost + weight(v,w)
– A notion of the lowest current known cost to unsettled.adjust() // re-order heap, O(ElogN)
3
Prim’s Algorithm for MCST Kruskal’s Algorithm for MCST
// Initially, one node in the spanning tree and no edges
PrimMCST(ref edge_set T) // T = set of edges in spanning tree
int closest[N] // closest[v] = vertex u in U closest to v
int lowcost[N] // lowcost[v] = weight[v,u]
// U is, implicitly, node 0 and the nodes connected to it by edges of T • Initially, each node is its own MCST
T = empty
for v in 1..N-1
• Merge two MCSTs at each step that can
lowcost[v] = weight[0,v]
closest[v] = 0 be connected together with the least cost
N-1 times do
// find the node closest to U and add it to U
min = lowcost[1]
adding the lowest cost edge
k=1
for j in 2..N-1 • Terminate when there is only 1 MCST that
if lowcost[j] < min
min = lowcost[j]
k=j
contains all vertices
//k is now the node outside U closest to something in U; add it to U
T += {(closest[k],k)} • Running time – O(ElogE)
lowcost[k] = infinity
for j in 1..N-1
if weight[k,j] < lowcost[j] && lowcost[j] < infinity
lowcost[j] = weight[k,j]
closest[j] = k