Page 1 of 35
CSE 100, UCSD:
LEC 12
Lecture 12
✔
Algorithms on graphs
✔
Breadth first, depth first searches
✔
Shortest path in unweighted graphs
✔
Greedy algorithms
✔
Djikstra’s algorithm for shortest path in weighted graphs
Reading:
Weiss, Chapter 9, 10

Page 2 of 35
CSE 100, UCSD:
LEC 12
Shortest path problems
✔
Suppose graph vertices represent computers, and graph edges represent network links
between computers, and edge weights represent communications times...
✗
... then a shortest-path algorithm can find the fastest route to send email between one
computer and another
✔
Suppose graph vertices represent cities, and graph edges represent airline routes
between cities, and edge weights represent travel costs ...
✗
... then a shortest-path algorithm can find the cheapest route to travel by air between
one city and another
✔
Many, many other examples...
✔
We will look at shortest-path algorithms in unweighted and weighted graphs
✔
These algorithms will find the shortest path from a “source” or “start” vertex to every
other vertex in the graph
✔
(Often you may want only the shortest path from a source vertex to one particular
destination vertex... but there is no known algorithm to do that with better worst-case
time cost than a good algorithm to find
shortest path to
every
other vertex!)

Page 3 of 35
CSE 100, UCSD:
LEC 12
The unweighted shortest path problem
✔
Input:
an unweighted directed graph G = (V,E) and a “source vertex”
s
in
V
✔
Output:
for each vertex
v
in V, a representation of the shortest path in G that starts at
s
and ends at
v
✔
What is the best approach to this problem?

Page 4 of 35
CSE 100, UCSD:
LEC 12
Search in graphs
✔
The shortest-path problem is a search problem in a graph:
starting at a vertex
s
, you are
searching for the shortest path to another vertex
v
✔
When searching in a graph, three important approaches are:
✗
depth-first search
✗
breadth-first search
✗
best-first search
✔
These approaches can be applied to many different search problems
✔
We’ll consider applying depth-first and breadth-first to the unweighted shortest-path
problem.
(Best-first will arise in the weighted shortest-path case)

Page 5 of 35
CSE 100, UCSD:
LEC 12
Breadth-first search
✔
Breadth-first search in a graph visits a node; and then all the nodes adjacent to that
node; then all the nodes adjacent to those nodes; etc.
✔
A level-order traversal of a tree is a breadth-first search:
1
2
3
4
5
6
7
8
10
9

Page 6 of 35
CSE 100, UCSD:
LEC 12
Depth first search
✔
Depth first search in a graph visits a node; and then recursively does depth-first search
from each of the nodes adjacent to that node
✔
A pre-order traversal of a tree is a depth-first search:
1
2
7
3
8
9
4
6
5
10

Page 7 of 35
CSE 100, UCSD:
LEC 12
Depth-first search for shortest paths
✔
Consider searching for shortest paths with start vertex V0
in this unweighted graph,
using depth-first search:
V0
V1
V4
V2
V3