Breadth-First Search
procedure BFS(G, src):
1: ► initialize all vertices (mark as not done)
2: for v ∈ V(G):
3: unmark v
4: reset parent (no parent yet)
5: reset distance (max possible)
6: distance of src is 0
7: ► load source vertex into a queue
8: Q ← MAKE-Q(src)
9: mark src
10: while Q ≠ ∅:
11: v ← POP(Q)
12: ► do something with v
13: ► explore v's neighbors
14: for u ∈ Adjacent(v):
15: if u is unmarked:
16: ► neighbor not finished, add to Q
17: mark u
18: v becomes u's parent
19: ADD(Q, u)
|
Dijkstra's Shortest Path
procedure DIJKSTRA(G, s):
1: ► initialize all vertices (source has distance 0)
2: for v ∈ V(G):
3: unmark v
4: reset parent (no parent yet)
5: reset distance (max possible)
6: distance of src is 0
7: ► load all vertices in a priority queue
8: PQ ← MAKE-PQ(V(G))
9: while PQ ≠ ∅:
10: v ← POP-MIN(PQ)
11: ► do something with v
12: ► explore v's neighbors
13: for u ∈ Adjacent(v):
14: if dist[u] > dist[v] + weight(v→u):
15: ► neighbor can be improved
16: ► this is not O(1) operation
17: dist[u] ← dist[v] + weight(v→u)
18: v becomes u's parent
|
Prim' Minimum Spanning Tree
procedure PRIM(G, s):
► initialize all vertices (source has distance 0)
for v ∈ V(G):
unmark v
reset parent (no parent yet)
reset distance (max possible)
distance of src is 0
► load all vertices in a priority queue
PQ ← MAKE-PQ(V(G))
► create a graph to represent the MST edges
T ← MAKE-GRAPH()
while PQ ≠ ∅:
v ← POP-MIN(PQ)
mark v
ADD(T, edge(v↔parent[v]))
► explore v's neighbors
for u ∈ Adjacent(v):
if u is unmarked and dist[u] > weight(v→u):
► neighbor can be improved
► this is not O(1) operation
dist[u] ← weight(v→u)
v becomes u's parent
|
Floyd-Warshall's All-Pairs Shortest Path
The algorithm builds a distance matrix, D , and predecessor matrix, P , based on the following recurrence:
/ D(i, j) , P(i, j) = P(i, j)
D(i, j) = min |
\ D(i, k) + D(k, j), P(i, j) = P(k, j)
where D and P are initialized as follows:
/ 0 if i = j
D(i, j) = | weight(i→j) if i ≠ j and edge i→j exists
\ ∞ otherwise
/ i if i ≠ j and edge i→j exists
P(i, j) = |
\ nil otherwise
procedure FLOYD-WARSHALL(G):
► initialize the adjacency and predecessor matrices
D, P ← ADJ-MATRIX(G)
► for each vertex in the graph
for k ∈ V(G):
► for each pair of vertices
for (i, j) ∈ V(G) × V(G):
► update the distance and predecessor matrices
► if detour through vertex k offers better distance
if D[i][k] + D[k][j] < D[i][j]:
D[i][j] ← D[i][k] + D[k][j]
P[i][j] ← P[k][j]
|
|