CH 13 Graphs
CH 13 Graphs
CHAPTER 13 Graphs
• Introduction to Graphs
• Searches
• Minimum Spanning Trees
• Topological Sorting with Directed Graphs
• Connectivity in Directed Graphs
1 2
3 4
3 4
Adjacency Paths
Two vertices are said to be adjacent to one another if they are A path is a sequence of edges. Figure 13.1 shows a path from
connected by a single edge. Thus, in Figure 13.1, vertices I and G vertex B to vertex J that passes through vertices A and E. We can
are adjacent, but vertices I and F are not. call this path BAEJ. There can be more than one path between two
vertices; another path from B to J is BCDJ.
5 6
5 6
1
7/20/2024
Connected Graphs
A graph is said to be connected if there is at least one path from
every vertex to every other vertex, as in the graph in Figure 13.2a. Directed and Weighted Graphs
The graphs in Figures 13.1 and 13.2 are non-directed graphs. That
A non-connected graph consists of several connected components. means that the edges don’t have a direction; you can go either way
In Figure 13.2b, A and B are one connected component, and C and on them. Thus, you can go from vertex A to vertex B, or from vertex B
D are another. to vertex A, with equal ease. (Non-directed graphs model freeways
appropriately, because you can usually go either way on a freeway.)
7 8
7 8
However, graphs are often used to model situations in which you In some graphs, edges are given a weight, a number that can
can go in only one direction along an edge—from A to B but represent the physical distance between two vertices, or the
not from B to A, as on a one-way street. Such a graph is said time it takes to get from one vertex to another, or how much it
to be directed. The allowed direction is typically shown with an costs to travel from vertex to vertex (on airline routes, for
arrowhead at the end of the edge. example). Such graphs are called weighted graphs.
9 10
9 10
11 12
11 12
2
7/20/2024
13 14
15 16
15 16
17 20
17 20
3
7/20/2024
Adding Vertices and Edges to a Graph If you are using an adjacency matrix and want to add an edge
To add a vertex to a graph, you make a new vertex object with between vertices 1 and 3. These numbers correspond to the
new and insert it into your vertex array, vertexList. In a real- array indices in vertexList where the vertices are stored.
world program a vertex might contain many data items, but for When you first created the adjacency matrix, you filled it with 0s.
simplicity we’ll assume that it contains only a single character. To insert the edge, you say
Thus, the creation of a vertex looks something like this:
adjMat[1][3] = 1;
vertexList[nVerts++] = new Vertex(‘F’); adjMat[3][1] = 1;
This inserts a vertex F, where nVerts is the number of vertices If you were using an adjacency list, you would add a 1 to the list
currently in the graph. for 3, and a 3 to the list for 1.
21 22
21 22
class Graph
The Graph Class {
Contains methods for creating a vertex list and an adjacency private final int MAX_VERTS = 20;
matrix, and for adding vertices and edges to a Graph object: private Vertex vertexList[]; // array of vertices
private int adjMat[][]; // adjacency matrix
private int nVerts; // current number of vertices
// -------------------------------------------------------------
public Graph() // constructor
{
vertexList = new Vertex[MAX_VERTS];
// adjacency matrix
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) // set adjacency
for(int k=0; k<MAX_VERTS; k++) // matrix to 0
adjMat[j][k] = 0;
} // end constructor
23 24
23 24
public void addVertex(char lab) // argument is label Exercise 1: Write a Graph methods
public void displayVertices() and public void displayEdges().
{ Demonstrate as follows:
vertexList[nVerts++] = new Vertex(lab);
Within the Graph class, vertices are identified
} public static void main(String[] args)
by their index number in vertexList. {
// ------------------------------------------------------------- Graph theGraph = new Graph();
public void addEdge(int start, int end) theGraph.addVertex('A'); // 0
theGraph.addVertex('B'); // 1
{
The adjacency matrix provides information theGraph.addVertex('C'); // 2
adjMat[start][end] = 1; that is local to a given vertex. Specifically, it theGraph.addVertex('D'); // 3
adjMat[end][start] = 1; tells you which vertices are connected by a theGraph.addVertex('E'); // 4
single edge to a given vertex. theGraph.addEdge(0, 1); // AB Vertices: ABCDE
} theGraph.addEdge(1, 2); // BC Edges:
theGraph.addEdge(0, 3); // AD A -- B
// ------------------------------------------------------------- A–D
theGraph.addEdge(3, 4); // DE
public void displayVertex(int v) System.out.print("Vertices: "); B–C
theGraph.displayVertices(); D -- E
{
System.out.println();
System.out.print(vertexList[v].label); System.out.println("Edges:");
} theGraph.displayEdges();
}
} // end class Graph
25
25 26
4
7/20/2024
Vertex 3:
D has out-degree:3
D has in-degree:2
27 28
Exercise 19.18*
System.out.println("\nEdges with tails less than heads:"); Write a Graph method public Graph transpose(): The
theGraph.tailLessThanHead(); executor returns a new Graph object that has the same vertices but the reversed edges,
i.e., an edge from v to w is in one if and only if an edge from w to v is in the other.
29 30
31 33
5
7/20/2024
Next, you go to any vertex adjacent to A that hasn’t yet been Applying Rule 1 again leads you to H. At this point, however, you
visited. You visit B, mark it, and push it on the stack. need to do something else because there are no unvisited
You’re at B, and you do the same thing as before: go to an vertices adjacent to H.
adjacent vertex that hasn’t been visited. This leads you to F.
RULE 2
If you can’t follow Rule 1, then, if possible, pop a vertex off the
RULE 1 stack.
If possible, visit an adjacent unvisited vertex, mark it, and push it
on the stack.
34 35
34 35
Following this rule, you pop H off the stack, which brings you You visit D, G, and I, and then pop them all when you reach the
back to F. F has no unvisited adjacent vertices, so you pop it. dead end at I. Now you’re back to A. You visit E, and again
Same for B. Now only A is left on the stack. you’re back to A.
36 37
36 37
38 39
38 39
6
7/20/2024
Java Code
A key to the DFS algorithm is being able to find the vertices that
are unvisited and adjacent to a specified vertex. How do you
do this? The adjacency matrix is the key.
Ignore the arrow heads By going to the row for the specified vertex and stepping across
the columns, you can pick out the columns with a 1; the
column number is the number of an adjacent vertex. You can
then check whether this vertex is unvisited. If so, you’ve found
what you want—the next vertex to visit.
If no vertices on the row are simultaneously 1 (adjacent) and
also unvisited, there are no unvisited vertices adjacent to the
specified vertex.
40 42
40 42
Now we’re ready for the dfs() method of the Graph class.
It loops until the stack is empty.
// returns an unvisited vertex adjacent to v
public int getAdjUnvisitedVertex(int v) Within the loop, it does four things:
{ 1. It examines the vertex at the top of the stack, using peek().
for(int j=0; j<nVerts; j++) 2. It tries to find an unvisited neighbor of this vertex.
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false) 3. If it doesn’t find one, it pops the stack.
return j; // return first such vertex 4. If it finds such a vertex, it visits that vertex and pushes it
return -1; // no such vertices onto the stack.
} // end getAdjUnvisitedVertex()
43 44
43 44
45 46
7
7/20/2024
49 50
49 50
Only some paths in a game tree lead to a successful conclusion. Breadth-First Search
For example, some lead to a win by your opponent. When you As we saw in the depth-first search, the algorithm acts as though
reach such an ending, you must back up, or backtrack, to a it wants to get as far away from the starting point as quickly as
previous node and try a different path. In this way you explore possible. In the breadth-first search, on the other hand, the
the tree until you find a path with a successful conclusion. algorithm likes to stay as close as possible to the starting
Then you make the first move along this path. point. It visits all the vertices adjacent to the starting vertex,
and only then goes further afield. This kind of search is
implemented using a queue instead of a stack.
51 52
51 52
53 54
53 54
8
7/20/2024
RULE 3 RULE 3
If you can’t carry out Rule 2 because the queue is empty, you’re If you can’t carry out Rule 2 because the queue is empty, you’re
done. done.
55 56
55 56
BCDEF There are no more unvisited vertices adjacent BCDEFG There are no more unvisited vertices adjacent
RULE 2 to A, so you remove B from the queue RULE 2 to A, so you remove B from the queue
and look for vertices adjacent to it. and look for vertices adjacent to it.
If you can’t carry out Rule 1 because there are no more unvisited If you can’t carry out Rule 1 because there are no more unvisited
Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There
are no more unvisited vertices adjacent to B, are no more unvisited vertices adjacent to B,
make it the current vertex. so you remove C from the queue. make it the current vertex. so you remove C from the queue.
57 58
57 58
BCDEFG There are no more unvisited vertices adjacent BCDEFGH There are no more unvisited vertices adjacent
RULE 2 to A, so you remove B from the queue RULE 2 to A, so you remove B from the queue
and look for vertices adjacent to it. and look for vertices adjacent to it.
If you can’t carry out Rule 1 because there are no more unvisited If you can’t carry out Rule 1 because there are no more unvisited
Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There
are no more unvisited vertices adjacent to B, are no more unvisited vertices adjacent to B,
make it the current vertex. so you remove C from the queue. make it the current vertex. so you remove C from the queue.
C has no adjacent unvisited vertices, so you C has no adjacent unvisited vertices, so you
RULE 3 remove D and visit G. RULE 3 remove D and visit G.
If you can’t carry out Rule 2 because the queue is empty, you’re If you can’t carry out Rule 2 because the queue is empty, you’re
D has no more adjacent unvisited vertices, so D has no more adjacent unvisited vertices, so
done. you remove E. done. you remove E.
59 60
9
7/20/2024
BCDEFGHI There are no more unvisited vertices adjacent BCDEFGHI There are no more unvisited vertices adjacent
RULE 2 to A, so you remove B from the queue RULE 2 to A, so you remove B from the queue
and look for vertices adjacent to it. and look for vertices adjacent to it.
If you can’t carry out Rule 1 because there are no more unvisited If you can’t carry out Rule 1 because there are no more unvisited
Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There Youthe
vertices, remove a vertex from find queue
F, so you (if
insert it in the queue.
possible) and There
are no more unvisited vertices adjacent to B, are no more unvisited vertices adjacent to B,
make it the current vertex. so you remove C from the queue. make it the current vertex. so you remove C from the queue.
C has no adjacent unvisited vertices, so you C has no adjacent unvisited vertices, so you
RULE 3 remove D and visit G. RULE 3 remove D and visit G.
If you can’t carry out Rule 2 because the queue is empty, you’re If you can’t carry out Rule 2 because the queue is empty, you’re
D has no more adjacent unvisited vertices, so D has no more adjacent unvisited vertices, so
done. you remove E. done. you remove E.
Now the queue is HI, but when you’ve Now the queue is HI, but when you’ve
removed each of these and found no removed each of these and found no
adjacent unvisited vertices, the queue is Now the queue is FG. You remove F and visit H, adjacent unvisited vertices, the queue is Now the queue is FG. You remove F and visit H,
empty, so you’re done. and then you remove G and visit I. 61 empty, so you’re done. and then you remove G and visit I. 62
61 62
63 64
traverses the tree or graph level-by-level, visiting the nodes of the tree above in the
order a b c d e f g h i j k.
65 66
65 66
10
7/20/2024
2
1 1
6 1
3 3 `
2 2
3
5
4 4
4
6 6
5 5
67 69
67 69
72 73
Graph theGraph = new Graph(); Consider the following graph. If there is ever a decision between
theGraph.addVertex(‘A’); // 0 (start for dfs) multiple neighbor nodes in the BFS or DFS algorithms, assume
theGraph.addVertex(‘B’); // 1 we always choose the letter closest to the beginning of the
theGraph.addVertex(‘C’); // 2 alphabet first.
theGraph.addVertex(‘D’); // 3
theGraph.addVertex(‘E’); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE
74 77
11
7/20/2024
Consider the following graph. If there is ever a decision between The breadth-first search has an interesting property: It first finds
multiple neighbor nodes in the BFS or DFS algorithms, assume all the vertices that are one edge away from the starting point,
we always choose the letter closest to the beginning of the then all the vertices that are two edges away, and so on.
alphabet first.
This is useful if you’re trying to find the shortest path (least
segments) from the starting vertex to a given vertex. You start
a BFS, and when you find the specified vertex, you know the
path you’ve traced so far has the least segments to the node.
78 79
78 79
Topological Sorting Arranged this way, the graph is said to be topologically sorted.
Imagine that you make a list of all the courses necessary for Any course you must take before some other course occurs
your degree, using Figure 13.11 as your input data. You then before it in the list.
arrange the courses in the order you need to take them. Actually, many possible orderings would satisfy the course
Obtaining your degree is the last item on the list, which might prerequisites. You could take the English courses C and F
look like this: BAEDGCFH first, for example: CFBAEDGH
80 81
80 81
The idea behind the topological sorting algorithm is unusual but STEP 2
simple. Two steps are necessary: Delete this vertex from the graph, and insert its label at the
STEP 1 beginning of a list.
Find a vertex that has no successors
Steps 1 and 2 are repeated until all the vertices are gone. At this
The successors to a vertex are those vertices that are directly point, the list shows the vertices arranged in topological order.
“downstream” from it— that is, connected to it by an edge that
points in their direction. If there is an edge pointing from A to
B, then B is a successor to A. In Figure 13.11, the only vertex
with no successors is H.
82 83
82 83
12
7/20/2024
The graph shown above has many valid topological sorts, including:
7, 5, 3, 11, 8, 2, 9, 10 (visual left-to-right, top-to-bottom)
3, 5, 7, 8, 11, 2, 9, 10 (smallest-numbered available vertex first)
5, 7, 3, 8, 11, 10, 9, 2 (fewest edges first)
7, 5, 11, 3, 10, 8, 9, 2 (largest-numbered
Wait !
available vertex first)
7, 5, 11, 2, 3, 8, 9, 10 (attempting top-to-bottom, left-to-right)
3, 7, 8, 5, 11, 10, 2, 9 (arbitrary)
wikipedia
84 85
84 85
wikipedia
86 87
86 87
88 89
13
7/20/2024
90 91
92 93
92 93
For a directed graph, the method that adds an edge thus needs Connectivity in Directed Graphs
only a single statement, We’ve seen how in a non-directed graph you can find all the
vertices that are connected by doing a depth-first or breadth-
public void addEdge(int start, int end) // directed graph first search.
{ When we try to find all the connected vertices in a directed
adjMat[start][end] = 1; graph, things get more complicated. You can’t just start from a
} randomly selected vertex and expect to reach all the other
connected vertices.
94 95
94 95
14
7/20/2024
Consider the graph in Figure 13.15. If you start on A, you can get The Connectivity Table
to C but not to any of the other vertices. If you start on B, you You can easily modify the dfs.java program (Listing 13.1) to start
can’t get to D, and if you start on C, you can’t get anywhere. the search on each vertex in turn. For the graph of Figure
The meaningful question about connectivity is: What vertices 13.15 the output will look something like this:
can you reach if you start on a particular vertex? AC
BACE
C
DEC
EC
This is the connectivity table for the directed graph. The first
letter is the starting vertex and subsequent letters show the
vertices that can be reached (either directly or via other
vertices) from the starting vertex.
96 97
96 97
98 99
98 99
Row A
We start with row A. There’s nothing in columns A and B, but there’s a 1
at column C, so we stop there.
Now the 1 at this location says there is a path from A to C. If we knew
there was a path from some vertex X to A, then we would know
We can use Warshall’s algorithm which is based on a there was a path from X to C.
simple idea: Where are the edges (if any) that end at A? They’re in column A. So we
If you can get from vertex L to vertex M, and you can get examine all the cells in column A. In Table 13.6 there’s only one 1 in
from M to N, then you can get from L to N. column A: at row B. It says there’s an edge from B to A. So we know
there’s an edge from B to A, and another (the one we started with)
from A to C. From this we infer that we can get from B to C in two
100
steps. 101
100 101
15
7/20/2024
1 1
To record this result, we put a 1 at the intersection of row B and column Row C has no 1s at all, so we go to row D. Here we find an edge from
C. D to E. However, column D is empty, so there are no edges that end
on D.
Rows B, C, and D
We go to row B. The first cell, at column A, has a 1, indicating an edge Row E
from B to A. In row E we see there’s an edge from E to C. Looking in column E we
Are there any edges that end at B? We look in column B, but it’s empty, see the first entry is for the edge B to E, so with B to E and E to C
so we know that none of the 1s we find in row B will result in finding we infer there’s a path from B to C. However, it’s already been
longer paths because no edges end at B. discovered, as indicated by the 1 at that location.
102 103
102 103
Warshall’s Algorithm
104 105
104 105
106 107
16
7/20/2024
Minimum Spanning Trees The number of edges E in a minimum spanning tree is always
Figure 13.10a shows five vertices with an excessive number of one less than the number of vertices V:
edges, while Figure 13.10b shows the same vertices with the E=V–1
minimum number of edges necessary to connect them. This The algorithm for creating the minimum spanning tree is almost
constitutes a minimum spanning tree (MST). identical to that used for searching. It can be based on either
the depth-first search or the breadth-first search. In this
example we’ll use the breadth-first search.
108 109
108 109
110 111
112 113
17
7/20/2024
114 115
114 115
Minimum Spanning Tree with Weighted Graphs An Example: Cable TV in the Jungle
When all edges are the same weight, it’s fairly straightforward— Suppose we want to install a cable television line that connects
as we saw earlier—for the algorithm to choose one to add to six towns. Five links will connect the six cities. The cost of
the minimum spanning tree. But when edges can have connecting each pair of cities varies, so we must pick the
different weights, some arithmetic is needed to choose the route carefully to minimize the overall cost.
right one.,
116 117
116 117
118 120
118 120
18
7/20/2024
121 122
121 122
You pick the least expensive one. So you build the Ajo–Danza Building the Ajo–Bordo Link
link and install an office in Danza before you can send out After you’ve completed the Ajo–Danza link and built your office in
surveyors from that town to adjacent towns. Danza, you can send out surveyors from Danza to all the
towns reachable from there Bordo, Colina, and Erizo.
• Ajo–Danza, $4 million
• Ajo–Bordo, $6 million
• Danza–Bordo, $7 million
• Danza–Colina, $8 million
• Danza–Erizo, $12 million
Why isn’t the Ajo–Danza link still on the list? Because you’ve
already installed the cable there; there’s no point giving any
further consideration to this link.
123 124
123 124
The Danza–Bordo link was on the previous list but is not on this
one because the two towns are already connected.
125 126
125 126
19
7/20/2024
• Bordo–Erizo, $7 million
Building the Erizo–Colina Link
• Danza–Colina, $8 million
From Erizo the surveyors report back costs of 5 million dollars to
• Bordo–Colina, $10 million
Colina and 7 to Flor.
• Danza–Erizo, $12 million
Your new list is
• Erizo–Colina, $5 million
From this list we can see that the cheapest route is Bordo–Erizo,
• Erizo–Flor, $7 million
at 7 million dollars. You send out the crew to install this cable
link, and you build an office in Erizo • Danza–Colina, $8 million
• Bordo–Colina, $10 million
127 128
127 128
You install the last link of cable from Colina to Flor, build an office
in Flor, and you’re done. You know you’re done because The applet should discover that the minimum spanning tree
there’s now an office in every town. consists of the edges AD, AB, BE, EC, and CF, for a total
edge weight of 28. The order in which the edges are specified
is unimportant. If you start at a different vertex, you will create
129 a tree with the same edges, but in a different order. 130
129 130
Repeat these steps until all the vertices are in the ms tree. At
that point, you’re done.
131 132
131 132
20
7/20/2024
A A
B D B D
C C
E F E F
133 134
133 134
Wait !
135 136
135 136
137 139
137 139
21
7/20/2024
140 141
140 141
Find the minimum-cost spanning tree in the graph given in the Find the minimum-cost spanning tree in the graph given in the
figure by using Kruskal’s algorithm. figure by using Prim’s algorithm, starting from the node 3.
142 143
142 143
144 145
144 145
22
7/20/2024
The railroad charges passengers a fixed fare to travel between The edges in Figure 14.6 are directed. They represent single-
any two towns. These fares are shown in Figure 14.6. That is, track railroad lines, on which (in the interest of safety) travel is
the fare from Ajo to Bordo is $50, from Bordo to Danza is $90, permitted in only one direction. For example, you can go
and so on. These rates are the same whether the ride directly from Ajo to Bordo, but not from Bordo to Ajo.
between two towns is part of a longer itinerary or not.
146 147
146 147
Although in this situation we’re interested in the cheapest fares, The shortest-path problem is this: For a given starting point and
the graph problem is nevertheless always referred to as the destination, what’s the cheapest route? In Figure 14.6, you
shortest-path problem (SPP). Here shortest doesn’t can see (with a little mental effort) that the cheapest route
necessarily mean shortest in terms of distance; it can also from Ajo to Erizo passes through Danza and Colina; it will cost
mean cheapest, fastest, or best route by some other you $140.
measure.
148 149
148 149
150 151
150 151
23
7/20/2024
infinity
152 153
Here, you pick the least expensive total route from Ajo to a town
with no agent.
154 155
154 155
The Second Agent: In Bordo Doing some quick arithmetic, you figure
The cheapest fare from Ajo is to Bordo, at $50. So you hire a it must be $50 plus $60, or $110 to
passerby and send him to Bordo, where he’ll be your agent. go from Ajo to Colina via Bordo, so
When he’s there, he calls you by telephone and tells you that you modify the entry for Colina. You
the Bordo stationmaster says it costs $60 to ride to Colina and also can see that, going via Bordo, it
$90 to Danza. must be $50 plus $90, or $140, from
Ajo to Danza. However—and this is
a key point—you already know it’s
only $80 going directly from Ajo to
Danza. You care only about the
cheapest route from Ajo, so you
ignore the more expensive route,
leaving this entry as it was.
156 157
156 157
24
7/20/2024
We’ll put a * next to Bordo (via Ajo) to show that there’s an agent The Third Agent: In Danza
in the town and that the cheapest fare to it is fixed. You hire another passerby and send her to Danza, with an $80
ticket. She reports that from Danza it’s $20 to Colina and $70
to Erizo. Now you can modify your entry for Colina.
158
100 (via Danza) 150 (via 159
Danza)
158 159
Now you can calculate that, since Colina is $100 from Ajo (via
The Fourth Agent: In Colina
Danza), and Erizo is $40 from Colina, you can reduce the
Now the cheapest path to any town without an agent is the $100 minimum Ajo-to-Erizo fare from $150 (the Ajo–Danza–Erizo
trip from Ajo to Colina, going via Danza. Accordingly, you route) to $140 (the Ajo–Danza–Colina–Erizo route).
dispatch an agent over this route to Colina. He reports that it’s
$40 from there to Erizo.
160 161
160 161
The Last Agent: In Erizo This narrative has demonstrated the essentials of Dijkstra’s
You dispatch an agent to Erizo, but she reports that there are no algorithm. The key points are
routes from Erizo to towns without agents. (There’s a route to • Each time you send an agent to a new town, you use the new
Bordo, but Bordo has an agent.) Table 14.6 shows the final information provided by that agent to revise your list of fares.
line in your notebook; all you’ve done is add a star to the Erizo Only the cheapest fare (that you know about) from the starting
entry to show that an agent is there. point to a given town is retained.
• You always send the new agent to the town that has the
cheapest path from the starting point (not the cheapest edge
from any town with an agent, as in the minimum spanning
tree).
162 163
162 163
25
7/20/2024
Consider the directed graph shown in the figure below. There are
multiple shortest path between vertices S and T. Which one
will be reported by Dijstra’s shortest path algorithm? Assume
that, in any iteration, the shortest path to a vertex v is updated
only when a strictly shorter path to v is discovered.
Using Dijstra’s shortest path algorithm, find the shortest path
from S to all other nodes showing the results after each step..
S A B C D E F G T
1 4 (via S) 3 (via S) inf 7 (via S) inf inf inf inf
164 165
164 165
S A B C D E F G T S A B C D E F G T
1 4 (via S) 3 (via S) inf 7 (via S) inf inf inf inf 1 4 (via S) 3 (via S) inf 7 (via S) inf inf inf inf
2 5 (via A) 8 (via D) 12 (via D) 10 (via D) 2 5 (via A) 8 (via D) 12 (via D) 10 (via D)
3 3 6 (via C)
4
166 167
166 167
S A B C D E F G T
1 4 (via S) 3 (via S) inf 7 (via S) inf inf inf inf A B C D E F G H I
2 5 (via A) 8 (via D) 12 (via D) 10 (via D)
3 6 (via C)
4 8 (via E)
168 169
168 169
26
7/20/2024
Homework : In the following graph, each vertex contains a letter that can Homework : In the following graph, each vertex contains a letter that can
be used to identify it. Each edge has a number next to it indicating its be used to identify it. Each edge has a number next to it indicating its
"length". Most edges are undirected; directed edges have an arrow on "length". Most edges are undirected; directed edges have an arrow on
them indicating their directionality. Calculate the shortest path from them indicating their directionality. Calculate the shortest path from
vertex a to vertex j using Dijkstra's algorithm. vertex a to vertex j using Dijkstra's algorithm.
a b c d e f g h i j a b c d e f g h i j
1 3(->a) 8(->a) 5(->a)
2 7(->d) 15(->c) 10(->b) 9(->d)
3 15(->f) 16(->f) 13(->g)
4 18(->h)
175 176
175 176
ShortestPath_Directed.java
ShortestPath.java
1 2 3
14
0 8 4
7 6 5
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 A B D G I H F C E
A B D G I H F C E 1 4(->0) 8(->0)
1 4(->A) 8(->A) 2 +8 12(->1) +1 9(->7) +7 15(->7)
2 12(->B) 9(->C) 15(->C) 3 +2 11(->6)
3 19(->D) 11(->F) 14(->D) 4 +14 25(->5) +14
4 28(->G) 21(->5)
5 +7 19(->2) +2 14(->2)
184 185
184 185
186 187
186 187
27
7/20/2024
188 189
Changing the starting vertex (or \reference vertex") does not We can also make a Hamilton circuit into its \mirror image"
change the Hamilton circuit, because the same edges are by reversing direction. The mirror image uses the same edges,
traversed in the same directions. but backwards, so it is not considered the same as the original
Hamilton circuit.
190 191
190 191
197 198
197 198
28
7/20/2024
199 200
199 200
201 202
201 202
203 204
29
7/20/2024
Is there a better way to tackle the TSP? Idea: At each stage in your tour, choose the closest vertex
That is, is there an optimal algorithm that is also efficient? that you have not visited yet.
205 206
205 206
It is quick and easy, but does not always find the lowest-weight Hamilton
circuit.
www.math.ku.edu/~jmartin/
207 208
207 208
i.e., in this weighted K16, which Hamilton circuit has the smallest
total weight?
209 210
30
7/20/2024
211 212
Then, he can pick the Hamilton circuit with the lowest total
weight of these sixteen.
21,049 km
But can Willy do better?
213 214
213 214
Apparently, using Alice Springs (AS) as the reference vertex yields the best
Hamilton circuit so far, namely
215 216
215 216
31
7/20/2024
217 218
217 218
32