Graph Traversing
Graph Traversing
G D C
destination
G
Call DFS on G
D found destination - done!
B Path is implicitly stored in DFS recursion
A Path is: A, B, D, G
Breadth-First Search: The Code
BFS(G, s) {
initialize vertices;
Q = {s}; // Q is a queue (duh); initialize to s
while (Q not empty) {
u = RemoveTop(Q);
for each v u->adj {
if (v->color == WHITE)
v->color = GREY;
v->d = u->d + 1;
v->p = u;
Enqueue(Q, v);
}
u->color = BLACK;
}
}
BFS
F B A start
BFS Process E
destination G D C
A B D C D
Initial call to BFS on A Dequeue A Dequeue B Dequeue C
Add A to queue Add B Add C, D Nothing to add
rear front
a) A B E D C F A
b) A B C D E F C B C
D
EBFA
c) B C D E F B A
F E
Example: Identifying Hamilton Circuits
Solution
a) It is a Hamilton circuit for the graph.
b) It is not a Hamilton circuit since it visits B
more than once.
c) It is not a Hamilton circuit since it does not
visit all the vertices.
Hamilton Circuits for Complete Graphs
Any complete graph with three of more vertices has a Hamilton circuit.
A 3 B
1 5
1 7
D 3 C
Example: Brute Force Algorithm
3
A B
Solution
1 1 5 7
Weight of circuit
D 3 C
1. A BCD A 14
14
3. A C BD A
4. A C D BA 12 (opposite of 2)
5. A D BC A 14 (opposite of 3)
6. A D CBA 14 (opposite of 1)
Nearest Neighbor Algorithm
Step 1: Choose a starting point. Call this vertex A.
Step 2: Check all the edges joined to A, and choose one that has the
smallest weight. Proceed along this edge to the next vertex.
Step 3: At each vertex you reach, check the edges from there to vertices not
yet visited. Choose the smallest weight. Proceed along this edge to the next
vertex.
Step 4: Repeat Step 3 until you have visited all the vertices.
Step 5: Return to the starting vertex.
Example: Nearest Neighbor
The time it takes to travel between points (in minutes) is shown on the
graph below. Use the nearest neighbor algorithm to approximate the least
time to visit each location.
A
9 20
13 9 3 E
B
8 8
10 5
C 7 D
Example: Nearest Neighbor Algorithm
Solution
Start Circuit Weight
A A D E BC A 40
B BE D C A B 37
C C D E BA C 37
D D E BA C D 37
E E BD C A E 51
Example: Nearest Neighbor Algorithm
From the information on the previous slide we would say that a route of
37 minutes should be about the least amount of time.
Note that
A BE C D A
has a total weight of 36 minutes. All we can expect from the nearest neighbor
algorithm is a reasonably good solution.