Graphs - Introduction and Breadth First Search

Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
Graphs
Introduction and Breadth First Search
Brad Miller
David Ranum1
1 Department
of Computer Science
Luther College
12/19/2005
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
Outline
1
Objectives
2
Vocabulary and Definitions
3
Representation
An Adjacency Matrix
An Adjacency List
Implementation
4
Graph Algorithms
A Breadth First Search
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
To learn what a graph is and how it is used.
To implement the graph abstract data type using multiple
internal representations.
To see how graphs can be used to solve a wide variety of
problems
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
Prerequisites for a Computer Science Major
Math-151
CS-150
CS-220
CS-151
CS-360
CS-250
CS-230
CS-490
CS-466
Graphs
CS-477
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Simple Example of a Directed Graph
V3
9
7
V4
3
1
8
V2
V5
1
4
2
V0
5
Graphs
V1
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
Graph() creates a new, empty graph.
addVertex(vert) adds an instance of Vertex to the
graph.
addEdge(fromVert, toVert) Adds a new, directed
edge to the graph that connects two vertices.
getVertex(vertKey) finds the vertex in the graph
named vertKey.
getVertices() returns the list of all vertices in the
graph.
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
Outline
1
Objectives
2
Vocabulary and Definitions
3
Representation
An Adjacency Matrix
An Adjacency List
Implementation
4
Graph Algorithms
A Breadth First Search
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
An Adjacency Matrix Representation for a Graph
V0
V0
V1
V2
V3
5
V1
4
9
V3
V5
V5
2
V2
V4
V4
7
1
1
8
Graphs
3
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
Outline
1
Objectives
2
Vocabulary and Definitions
3
Representation
An Adjacency Matrix
An Adjacency List
Implementation
4
Graph Algorithms
A Breadth First Search
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
An Adjacency List Representation of a Graph
V0
V1
V1
V2
V2
V3
V3
V4
V4
V0
V5
V2
V5
V5
V4
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
Outline
1
Objectives
2
Vocabulary and Definitions
3
Representation
An Adjacency Matrix
An Adjacency List
Implementation
4
Graph Algorithms
A Breadth First Search
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
The Vertex Class I
1
2
3
4
5
6
7
8
9
10
c l a s s Vertex:
d e f __init__(self,num):
self.id = num
self.adj = []
self.color = ’white’
self.dist = sys.maxint
self.pred = None
self.disc = 0
self.fin = 0
self.cost = {}
11
12
13
14
d e f addNeighbor(self,nbr,cost=0):
self.adj.append(nbr)
self.cost[nbr] = cost
15
16
d e f __str__(self):
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
The Vertex Class II
17
18
19
r e t u r n str(self.id) + ":color " + self.color + \
":dist " + str(self.dist) +
":pred [" + str(self.pred)+ "]\n"
20
21
22
23
24
25
26
27
28
29
30
31
32
33
d e f getCost(self,nbr):
r e t u r n self.cost[nbr]
d e f setCost(self,nbr,cost):
self.cost[nbr] = cost
d e f setColor(self,color):
self.color = color
d e f setDistance(self,d):
self.dist = d
d e f setPred(self,p):
self.pred = p
d e f setDiscovery(self,dtime):
self.disc = dtime
d e f setFinish(self,ftime):
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
The Vertex Class III
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
self.fin = ftime
d e f getFinish(self):
r e t u r n self.fin
d e f getDiscovery(self):
r e t u r n self.disc
d e f getPred(self):
r e t u r n self.pred
d e f getDistance(self):
r e t u r n self.dist
d e f getColor(self):
r e t u r n self.color
d e f getAdj(self):
r e t u r n self.adj
d e f getId(self):
r e t u r n self.id
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
The Graph Class I
1
2
3
4
c l a s s Graph:
d e f __init__(self):
self.vertList = {}
self.numVertices = 0
5
6
7
8
9
10
d e f addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertList[key] = newVertex
r e t u r n newVertex
11
12
13
14
15
16
d e f getVertex(self,n):
i f self.vertList.has_key(n):
r e t u r n self.vertList[n]
else:
r e t u r n None
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
An Adjacency Matrix
An Adjacency List
Implementation
The Graph Class II
17
18
19
d e f has_key(self,n):
r e t u r n self.vertList.has_key(n)
20
21
22
23
24
25
26
d e f addEdge(self,f,t,c=0):
i f n o t self.vertList.has_key(f):
nv = self.addVertex(f)
i f n o t self.vertList.has_key(t):
nv = self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t],c)
27
28
29
d e f getVertices(self):
r e t u r n self.vertList.values()
30
31
32
d e f __iter__(self):
r e t u r n self.vertList.itervalues()
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Outline
1
Objectives
2
Vocabulary and Definitions
3
Representation
An Adjacency Matrix
An Adjacency List
Implementation
4
Graph Algorithms
A Breadth First Search
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Represent the relationships between the words as a graph.
Use the graph algorithm known as breadth first search to
find an efficient path from the starting word to the ending
word.
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
A Small Word Ladder Graph
fail
fall
foil
pall
pope
sale
foul
pole
pale
sage
fool
poll
page
cool
pool
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Building a Graph of Words for the Word Ladder
Problem I
1
2
3
4
5
6
7
8
9
10
11
12
13
14
d e f buildGraph():
d = {}
g = Graph()
wfile = file(’words.dat’)
# create buckets of words that differ by one letter.
f o r line i n wfile:
word = line[0:5]
f o r i i n range(5):
bucket = word[0:i] + ’_’ + word[i+1:5]
i f d.has_key(bucket):
d[bucket].append(word)
else:
d[bucket] = [word]
# add vertices and edges for words in the same bucket.
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Building a Graph of Words for the Word Ladder
Problem II
15
16
17
18
19
20
f o r i i n d.keys():
f o r j i n d[i]:
f o r k i n d[i]:
i f j != k:
g.addEdge(j,k)
return g
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
1
The new, unexplored vertex v, is colored gray.
2
The predecessor of v is set to the current node w
3
The distance to v is set to the distance to w + 1
4
v is added to the end of a queue. Adding v to the end of
the queue effectively schedules this node for further
exploration, but not until all the other vertices on the
adjacency list of w have been explored.
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Breadth First Search I
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
d e f bfs(g,vertKey):
s = g.getVertex(vertKey)
s.setDistance(0)
s.setPred(None)
s.setColor(’gray’)
Q = Queue()
Q.enqueue(s)
w h i l e (Q.size() > 0):
w = Q.dequeue()
f o r v i n w.getAdj():
i f (v.getColor() == ’white’):
v.setColor(’gray’)
v.setDistance( w.getDistance() + 1 )
v.setPred(w)
Q.enqueue(v)
w.setColor(’black’)
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Fist Step in the Breadth First Search
fool
pool
1
Queue
foil
1
pool
foul
1
foil
foul
Graphs
cool
1
cool
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
The Second Step in the Breadth First Search
fool
pool
1
foil
1
foul
1
poll
2
Queue
foil
foul
cool
poll
Graphs
cool
1
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
Constructing the Breadth First Search Tree
fool
fool
pool
1
foil
1
foul
1
cool
1
pool
1
foil
1
poll
2
fail
2
pole
3
poll
2
fail
2
Queue
pole
pall
foul
1
cool
1
pall
3
pope
4
pale
4
page
5
sale
5
Queue
sage
6
(a) Breadth First Search Tree After (b) Final Breadth First Search Tree
Completing One Level
Graphs
Objectives
Vocabulary and Definitions
Representation
Graph Algorithms
A Breadth First Search
You can represent your problem in terms of an unweighted
graph.
The solution to your problem is to find the shortest path
between two nodes in the graph.
Graphs