Graphs - Introduction and Breadth First...

27
Objectives Vocabulary and Definitions Representation Graph Algorithms Graphs Introduction and Breadth First Search Brad Miller David Ranum 1 1 Department of Computer Science Luther College 12/19/2005 Graphs

Transcript of Graphs - Introduction and Breadth First...

Page 1: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

GraphsIntroduction and Breadth First Search

Brad Miller David Ranum1

1Department of Computer ScienceLuther College

12/19/2005

Graphs

Page 2: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

Outline

1 Objectives

2 Vocabulary and Definitions

3 RepresentationAn Adjacency MatrixAn Adjacency ListImplementation

4 Graph AlgorithmsA Breadth First Search

Graphs

Page 3: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

To learn what a graph is and how it is used.To implement the graph abstract data type using multipleinternal representations.To see how graphs can be used to solve a wide variety ofproblems

Graphs

Page 4: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

Prerequisites for a Computer Science Major

Math-151 CS-220

CS-150 CS-151

CS-230CS-250

CS-360

CS-477CS-466

CS-490

Graphs

Page 5: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Simple Example of a Directed Graph

V0 V15

V5

2

V2

4

1V4 8

V3

9

37

1

Graphs

Page 6: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

Graph() creates a new, empty graph.addVertex(vert) adds an instance of Vertex to thegraph.addEdge(fromVert, toVert) Adds a new, directededge to the graph that connects two vertices.getVertex(vertKey) finds the vertex in the graphnamed vertKey.getVertices() returns the list of all vertices in thegraph.

Graphs

Page 7: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

Outline

1 Objectives

2 Vocabulary and Definitions

3 RepresentationAn Adjacency MatrixAn Adjacency ListImplementation

4 Graph AlgorithmsA Breadth First Search

Graphs

Page 8: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

An Adjacency Matrix Representation for a Graph

V0 V1 V2 V3 V4 V5

V0 5 2

V1 4

V2 9

V3 7 3

V4 1

V5 1 8

Graphs

Page 9: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

Outline

1 Objectives

2 Vocabulary and Definitions

3 RepresentationAn Adjacency MatrixAn Adjacency ListImplementation

4 Graph AlgorithmsA Breadth First Search

Graphs

Page 10: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

An Adjacency List Representation of a Graph

V1

V2

V3

V4

V0

V2

V0

V1

V2

V3

V4

V5

V5

V5

V4

Graphs

Page 11: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

Outline

1 Objectives

2 Vocabulary and Definitions

3 RepresentationAn Adjacency MatrixAn Adjacency ListImplementation

4 Graph AlgorithmsA Breadth First Search

Graphs

Page 12: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

The Vertex Class I

1 c l a s s Vertex:2 def __init__(self,num):3 self.id = num4 self.adj = []5 self.color = ’white’6 self.dist = sys.maxint7 self.pred = None8 self.disc = 09 self.fin = 0

10 self.cost = {}11

12 def addNeighbor(self,nbr,cost=0):13 self.adj.append(nbr)14 self.cost[nbr] = cost15

16 def __str__(self):

Graphs

Page 13: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

The Vertex Class II

17 re turn str(self.id) + ":color " + self.color + \18 ":dist " + str(self.dist) +19 ":pred [" + str(self.pred)+ "]\n"20

21 def getCost(self,nbr):22 re turn self.cost[nbr]23 def setCost(self,nbr,cost):24 self.cost[nbr] = cost25 def setColor(self,color):26 self.color = color27 def setDistance(self,d):28 self.dist = d29 def setPred(self,p):30 self.pred = p31 def setDiscovery(self,dtime):32 self.disc = dtime33 def setFinish(self,ftime):

Graphs

Page 14: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

The Vertex Class III

34 self.fin = ftime35 def getFinish(self):36 re turn self.fin37 def getDiscovery(self):38 re turn self.disc39 def getPred(self):40 re turn self.pred41 def getDistance(self):42 re turn self.dist43 def getColor(self):44 re turn self.color45 def getAdj(self):46 re turn self.adj47 def getId(self):48 re turn self.id

Graphs

Page 15: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

The Graph Class I

1 c l a s s Graph:2 def __init__(self):3 self.vertList = {}4 self.numVertices = 05

6 def addVertex(self,key):7 self.numVertices = self.numVertices + 18 newVertex = Vertex(key)9 self.vertList[key] = newVertex

10 re turn newVertex11

12 def getVertex(self,n):13 i f self.vertList.has_key(n):14 re turn self.vertList[n]15 e l s e:16 re turn None

Graphs

Page 16: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

An Adjacency MatrixAn Adjacency ListImplementation

The Graph Class II

17

18 def has_key(self,n):19 re turn self.vertList.has_key(n)20

21 def addEdge(self,f,t,c=0):22 i f not self.vertList.has_key(f):23 nv = self.addVertex(f)24 i f not self.vertList.has_key(t):25 nv = self.addVertex(t)26 self.vertList[f].addNeighbor(self.vertList[t],c)27

28 def getVertices(self):29 re turn self.vertList.values()30

31 def __iter__(self):32 re turn self.vertList.itervalues()

Graphs

Page 17: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Outline

1 Objectives

2 Vocabulary and Definitions

3 RepresentationAn Adjacency MatrixAn Adjacency ListImplementation

4 Graph AlgorithmsA Breadth First Search

Graphs

Page 18: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Represent the relationships between the words as a graph.Use the graph algorithm known as breadth first search tofind an efficient path from the starting word to the endingword.

Graphs

Page 19: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

A Small Word Ladder Graph

fool

pool

foul

cool

foil

poll

fail

pole

pall

pale

pope

fall

sale

page

sage

Graphs

Page 20: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Building a Graph of Words for the Word LadderProblem I

1 def buildGraph():2 d = {}3 g = Graph()4 wfile = file(’words.dat’)5 # create buckets of words that differ by one letter.6 f o r line in wfile:7 word = line[0:5]8 f o r i in range(5):9 bucket = word[0:i] + ’_’ + word[i+1:5]

10 i f d.has_key(bucket):11 d[bucket].append(word)12 e l s e:13 d[bucket] = [word]14 # add vertices and edges for words in the same bucket.

Graphs

Page 21: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Building a Graph of Words for the Word LadderProblem II

15 f o r i in d.keys():16 f o r j in d[i]:17 f o r k in d[i]:18 i f j != k:19 g.addEdge(j,k)20 re turn g

Graphs

Page 22: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph 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 ofthe queue effectively schedules this node for furtherexploration, but not until all the other vertices on theadjacency list of w have been explored.

Graphs

Page 23: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Breadth First Search I

1 def bfs(g,vertKey):2 s = g.getVertex(vertKey)3 s.setDistance(0)4 s.setPred(None)5 s.setColor(’gray’)6 Q = Queue()7 Q.enqueue(s)8 whi le (Q.size() > 0):9 w = Q.dequeue()

10 f o r v in w.getAdj():11 i f (v.getColor() == ’white’):12 v.setColor(’gray’)13 v.setDistance( w.getDistance() + 1 )14 v.setPred(w)15 Q.enqueue(v)16 w.setColor(’black’)

Graphs

Page 24: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Fist Step in the Breadth First Search

fool

pool1

foil1

foul1

cool1

pool foil foul coolQueue

Graphs

Page 25: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

The Second Step in the Breadth First Search

fool

pool1

foil1

foul1

cool1

pollfoil foul coolQueue

poll2

Graphs

Page 26: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

Constructing the Breadth First Search Tree

fool

pool1

foil1

foul1

cool1

pole pallQueue

poll2

fail2

(a) Breadth First Search Tree AfterCompleting One Level

fool

pool1

foil1

foul1

cool1

Queue

poll2

fail2

pole3

pall3

pope4

pale4

page5

sale5

sage6

(b) Final Breadth First Search Tree

Graphs

Page 27: Graphs - Introduction and Breadth First Searchcoral.ie.lehigh.edu/~ted/files/ie172/lectures/graphIntro... · 2016. 3. 26. · 1 The new, unexplored vertex v, is colored gray. 2 The

ObjectivesVocabulary and Definitions

RepresentationGraph Algorithms

A Breadth First Search

You can represent your problem in terms of an unweightedgraph.The solution to your problem is to find the shortest pathbetween two nodes in the graph.

Graphs