CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph...

59
CSC311: Data Structures CSC311: Data Structures 1 Chapter 13: Graphs I Chapter 13: Graphs I Objectives: Objectives: Graph ADT: Operations Graph ADT: Operations Graph Implementation: Data Graph Implementation: Data structures structures Graph Traversals: DFS and BFS Graph Traversals: DFS and BFS Directed graphs Directed graphs Weighted graphs Weighted graphs Shortest paths Shortest paths Minimum Spanning Trees (MST) Minimum Spanning Trees (MST)
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    251
  • download

    0

Transcript of CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph...

Page 1: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

CSC311: Data StructuresCSC311: Data Structures 11

Chapter 13: Graphs IChapter 13: Graphs I

Objectives:Objectives:

Graph ADT: OperationsGraph ADT: Operations Graph Implementation: Data structuresGraph Implementation: Data structures Graph Traversals: DFS and BFSGraph Traversals: DFS and BFS Directed graphsDirected graphs Weighted graphsWeighted graphs Shortest pathsShortest paths Minimum Spanning Trees (MST)Minimum Spanning Trees (MST)

Page 2: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 22

GraphsGraphsA graph is a pair A graph is a pair ((V, EV, E)), where, where– VV is a set of nodes, called is a set of nodes, called verticesvertices– EE is a collection of pairs of vertices, called is a collection of pairs of vertices, called edgesedges– Vertices and edges are positions and store elementsVertices and edges are positions and store elements

Example:Example:– A vertex represents an airport and stores the three-letter airport A vertex represents an airport and stores the three-letter airport

codecode– An edge represents a flight route between two airports and An edge represents a flight route between two airports and

stores the mileage of the routestores the mileage of the route

ORD PVD

MIADFW

SFO

LAX

LGA

HNL

849

802

13871743

1843

10991120

1233337

2555

142

Page 3: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 33

Edge TypesEdge TypesDirected edgeDirected edge– ordered pair of verticesordered pair of vertices ( (uu,,vv))– first vertex first vertex uu is the origin is the origin– second vertex second vertex vv is the is the

destinationdestination– e.g., a flighte.g., a flight

Undirected edgeUndirected edge– unordered pair of verticesunordered pair of vertices ( (uu,,vv))– e.g., a flight routee.g., a flight route

Directed graphDirected graph– all the edges are directedall the edges are directed– e.g., route networke.g., route network

Undirected graphUndirected graph– all the edges are undirectedall the edges are undirected– e.g., flight networke.g., flight network

ORD PVDflight

AA 1206

ORD PVD849

miles

Page 4: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 44

John

DavidPaul

brown.edu

cox.net

cs.brown.edu

att.netqwest.net

math.brown.edu

cslab1bcslab1a

ApplicationsApplicationsElectronic circuitsElectronic circuits– Printed circuit boardPrinted circuit board– Integrated circuitIntegrated circuit

Transportation networksTransportation networks– Highway networkHighway network– Flight networkFlight network

Computer networksComputer networks– Local area networkLocal area network– InternetInternet– WebWeb

DatabasesDatabases– Entity-relationship diagramEntity-relationship diagram

Page 5: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 55

TerminologyTerminologyEnd vertices (or endpoints) End vertices (or endpoints) of an edgeof an edge– U and V are the endpoints U and V are the endpoints

of aof a

Edges incident on a vertexEdges incident on a vertex– a, d, and b are incident on a, d, and b are incident on

VV

Adjacent verticesAdjacent vertices– U and V are adjacentU and V are adjacent

Degree of a vertexDegree of a vertex– X has degree 5 X has degree 5

Parallel edgesParallel edges– h and i are parallel edgesh and i are parallel edges

Self-loopSelf-loop– j is a self-loopj is a self-loop

XU

V

W

Z

Y

a

c

b

e

d

f

g

h

i

j

Page 6: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 66

P1

Terminology (cont.)Terminology (cont.)PathPath– sequence of alternating sequence of alternating

vertices and edges vertices and edges – begins with a vertexbegins with a vertex– ends with a vertexends with a vertex– each edge is preceded and each edge is preceded and

followed by its endpointsfollowed by its endpoints

Simple pathSimple path– path such that all its vertices path such that all its vertices

and edges are distinctand edges are distinct

ExamplesExamples– PP11=(V,b,X,h,Z)=(V,b,X,h,Z) is a simple is a simple

pathpath– PP22=(U,c,W,e,X,g,Y,f,W,d,V)=(U,c,W,e,X,g,Y,f,W,d,V) is is

a path that is not simplea path that is not simple

XU

V

W

Z

Y

a

c

b

e

d

f

g

hP2

Page 7: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 77

Terminology (cont.)Terminology (cont.)CycleCycle– circular sequence of alternating circular sequence of alternating

vertices and edges vertices and edges – each edge is preceded and each edge is preceded and

followed by its endpointsfollowed by its endpoints

Simple cycleSimple cycle– cycle such that all its vertices cycle such that all its vertices

and edges are distinctand edges are distinct

ExamplesExamples– CC11=(V,b,X,g,Y,f,W,c,U,a,=(V,b,X,g,Y,f,W,c,U,a,)) is a is a

simple cyclesimple cycle

– CC22=(U,c,W,e,X,g,Y,f,W,d,V,a,=(U,c,W,e,X,g,Y,f,W,d,V,a,)) is a cycle that is not simpleis a cycle that is not simple

C1

XU

V

W

Z

Y

a

c

b

e

d

f

g

hC2

Page 8: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 88

PropertiesProperties

NotationNotation nn number of verticesnumber of vertices

mm number of edgesnumber of edges

deg(deg(vv)) degree of vertex degree of vertex vv

Property 1Property 1

v v deg(deg(vv)) 22mm

Proof:Proof: each edge is each edge is counted twicecounted twice

Property 2Property 2In an undirected graph In an undirected graph

with no self-loops and with no self-loops and no multiple edgesno multiple edges

m m n n ((n n 1)1)22Proof:Proof: each vertex has each vertex has

degree at most degree at most ((n n 1)1)

What is the bound for a What is the bound for a directed graph?directed graph?

ExampleExample– n n 44

– m m 66

– deg(deg(vv)) 33

Page 9: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 99

Main Methods of the Graph ADTMain Methods of the Graph ADTVertices and edgesVertices and edges– are positionsare positions– store elementsstore elements

Accessor methodsAccessor methods– endVerticesendVertices(e): an array (e): an array

of the two endvertices of of the two endvertices of ee

– oppositeopposite(v, e): the vertex (v, e): the vertex opposite of v on eopposite of v on e

– areAdjacentareAdjacent(v, w): true iff (v, w): true iff v and w are adjacentv and w are adjacent

– replacereplace(v, x): replace (v, x): replace element at vertex v with xelement at vertex v with x

– replacereplace(e, x): replace (e, x): replace element at edge e with xelement at edge e with x

Update methodsUpdate methods– insertVertexinsertVertex(o): insert a (o): insert a

vertex storing element overtex storing element o– insertEdgeinsertEdge(v, w, o): insert (v, w, o): insert

an edge (v,w) storing an edge (v,w) storing element oelement o

– removeVertexremoveVertex(v): remove (v): remove vertex v (and its incident vertex v (and its incident edges)edges)

– removeEdgeremoveEdge(e): remove (e): remove edge eedge e

Iterator methodsIterator methods– incidentEdgesincidentEdges(v): edges (v): edges

incident to vincident to v– verticesvertices(): all vertices in the (): all vertices in the

graphgraph– edgesedges(): all edges in the (): all edges in the

graphgraph

Page 10: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1010

Edge List StructureEdge List StructureVertex objectVertex object– elementelement– reference to position in reference to position in

vertex sequencevertex sequence

Edge objectEdge object– elementelement– origin vertex objectorigin vertex object– destination vertex objectdestination vertex object– reference to position in reference to position in

edge sequenceedge sequence

Vertex sequenceVertex sequence– sequence of vertex sequence of vertex

objectsobjects

Edge sequenceEdge sequence– sequence of edge objectssequence of edge objects

v

u

w

a c

b

a

zd

u v w z

b c d

Page 11: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1111

Adjacency List StructureAdjacency List Structure

Edge list structureEdge list structureIncidence sequence Incidence sequence for each vertexfor each vertex– sequence of sequence of

references to edge references to edge objects of incident objects of incident edgesedges

Augmented edge Augmented edge objectsobjects– references to references to

associated positions associated positions in incidence in incidence sequences of end sequences of end verticesvertices

u

v

w

a b

a

u v w

b

Page 12: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1212

Adjacency Matrix StructureAdjacency Matrix StructureEdge list structureEdge list structureAugmented vertex Augmented vertex objectsobjects– Integer key (index) Integer key (index)

associated with vertexassociated with vertex

2D-array adjacency 2D-array adjacency arrayarray– Reference to edge Reference to edge

object for adjacent object for adjacent verticesvertices

– Null for non Null for non nonadjacent verticesnonadjacent vertices

The “old fashioned” The “old fashioned” version just has 0 for no version just has 0 for no edge and 1 for edgeedge and 1 for edge

u

v

w

a b

00 11 22

00

11

22 a

u v w0 1 2

b

Page 13: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1313

Asymptotic PerformanceAsymptotic Performance nn vertices, vertices, mm edges edges

no parallel edgesno parallel edges

no self-loopsno self-loops

Bounds are “big-Oh”Bounds are “big-Oh”

EdgeEdgeListList

AdjacencyAdjacencyListList

AdjacencAdjacency Matrixy Matrix

SpaceSpace n n m m n n m m nn22

incidentEdgesincidentEdges((vv)) mm deg(deg(vv)) nn

areAdjacent areAdjacent ((v, wv, w)) mm min(deg(min(deg(vv), deg(), deg(ww)))) 11

insertVertexinsertVertex((oo)) 11 11 nn22

insertEdgeinsertEdge((v, w, ov, w, o)) 11 11 11

removeVertexremoveVertex((vv)) mm deg(deg(vv)) nn22

removeEdgeremoveEdge((ee)) 11 11 11

Page 14: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1414

SubgraphsSubgraphsA subgraph S of a A subgraph S of a graph G is a graph graph G is a graph such that such that – The vertices of S are a The vertices of S are a

subset of the vertices of subset of the vertices of GG

– The edges of S are a The edges of S are a subset of the edges of subset of the edges of GG

A spanning subgraph A spanning subgraph of G is a subgraph that of G is a subgraph that contains all the contains all the vertices of Gvertices of G

Subgraph

Spanning subgraph

Page 15: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1515

ConnectivityConnectivity

A graph is A graph is connected if there connected if there is a path between is a path between every pair of every pair of verticesverticesA connected A connected component of a component of a graph G is a graph G is a maximal connected maximal connected subgraph of Gsubgraph of G

Connected graph

Non connected graph with two connected components

Page 16: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1616

Trees and ForestsTrees and ForestsA (free) tree is an A (free) tree is an undirected graph T undirected graph T such thatsuch that– T is connectedT is connected– T has no cyclesT has no cyclesThis definition of tree is This definition of tree is

different from the one different from the one of a rooted treeof a rooted tree

A forest is an A forest is an undirected graph undirected graph without cycleswithout cyclesThe connected The connected components of a components of a forest are treesforest are trees

Tree

Forest

Page 17: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1717

Spanning Trees and ForestsSpanning Trees and Forests

A spanning tree of a A spanning tree of a connected graph is a connected graph is a spanning subgraph that is spanning subgraph that is a treea treeA spanning tree is not A spanning tree is not unique unless the graph unique unless the graph is a treeis a treeSpanning trees have Spanning trees have applications to the design applications to the design of communication of communication networksnetworksA spanning forest of a A spanning forest of a graph is a spanning graph is a spanning subgraph that is a forestsubgraph that is a forest

Graph

Spanning tree

Page 18: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1818

Depth-First SearchDepth-First SearchDepth-first search Depth-first search (DFS) is a general (DFS) is a general technique for technique for traversing a graphtraversing a graphA DFS traversal of a A DFS traversal of a graph G graph G – Visits all the vertices Visits all the vertices

and edges of Gand edges of G– Determines whether G Determines whether G

is connectedis connected– Computes the Computes the

connected connected components of Gcomponents of G

– Computes a spanning Computes a spanning forest of Gforest of G

DFS on a graph with DFS on a graph with nn vertices and vertices and mm edges edges takes takes OO((nnmm ) ) time time

DFS can be further DFS can be further extended to solve other extended to solve other graph problemsgraph problems– Find and report a path Find and report a path

between two given verticesbetween two given vertices– Find a cycle in the graphFind a cycle in the graph

Depth-first search is to Depth-first search is to graphs while Euler tour is graphs while Euler tour is to binary treesto binary trees

Page 19: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 1919

DFS AlgorithmDFS AlgorithmThe algorithm uses a The algorithm uses a mechanism for setting and mechanism for setting and getting “labels” of vertices getting “labels” of vertices and edgesand edges Algorithm DFS(G, v)

Input graph G and a start vertex v of G Output labeling of the edges of G

in the connected component of v as discovery edges and back edges

setLabel(v, VISITED)for all e G.incidentEdges(v)

if getLabel(e) UNEXPLORED

w opposite(v,e)if getLabel(w)

UNEXPLOREDsetLabel(e, DISCOVERY)DFS(G, w)

elsesetLabel(e, BACK)

Algorithm DFS(G)Input graph GOutput labeling of the edges of G

as discovery edges andback edges

for all u G.vertices()setLabel(u, UNEXPLORED)

for all e G.edges()setLabel(e, UNEXPLORED)

for all v G.vertices()if getLabel(v)

UNEXPLOREDDFS(G, v)

Page 20: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2020

ExampleExample

DB

A

C

E

DB

A

C

E

DB

A

C

E

discovery edgeback edge

A visited vertex

A unexplored vertex

unexplored edge

Page 21: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2121

Example (cont.)Example (cont.)

DB

A

C

E

DB

A

C

E

DB

A

C

E

DB

A

C

E

Page 22: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2222

Properties of DFSProperties of DFS

Property 1Property 1DFSDFS((G, vG, v) ) visits all the visits all the vertices and edges in vertices and edges in the connected the connected component of component of vv

Property 2Property 2The discovery edges The discovery edges labeled by labeled by DFSDFS((G, vG, v) ) form a spanning tree form a spanning tree of the connected of the connected component of component of vv

DB

A

C

E

Page 23: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2323

Analysis of DFSAnalysis of DFSSetting/getting a vertex/edge label takes Setting/getting a vertex/edge label takes OO(1)(1) time timeEach vertex is labeled twice Each vertex is labeled twice – once as UNEXPLOREDonce as UNEXPLORED– once as once as VISITEDVISITED

Each edge is labeled twiceEach edge is labeled twice– once as UNEXPLOREDonce as UNEXPLORED– once as once as DISCOVERYDISCOVERY or or BACKBACK

Method incidentEdges is called once for each Method incidentEdges is called once for each vertexvertexDFS runs in DFS runs in OO((n n m m)) time provided the graph is time provided the graph is represented by the adjacency list structurerepresented by the adjacency list structure– Recall that Recall that v v deg(deg(vv)) 22mm

Page 24: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2424

Path FindingPath FindingWe can specialize the DFS We can specialize the DFS algorithm to find a path algorithm to find a path between two given between two given vertices vertices uu and and zz using the using the template method patterntemplate method patternWe call We call DFSDFS((G, uG, u) ) with with uu as as the start vertexthe start vertexWe use a stack We use a stack SS to keep to keep track of the path between track of the path between the start vertex and the the start vertex and the current vertexcurrent vertexAs soon as destination As soon as destination vertex vertex zz is encountered, we is encountered, we return the path as the return the path as the contents of the stack contents of the stack

Algorithm pathDFS(G, v, z)setLabel(v, VISITED)S.push(v)if v z

return S.elements()for all e G.incidentEdges(v)

if getLabel(e) UNEXPLORED

w opposite(v,e)if getLabel(w)

UNEXPLORED setLabel(e, DISCOVERY)S.push(e)pathDFS(G, w, z)S.pop(e)

else setLabel(e, BACK)

S.pop(v)

Page 25: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2525

Cycle FindingCycle FindingWe can specialize the We can specialize the DFS algorithm to find a DFS algorithm to find a simple cycle using the simple cycle using the template method template method patternpattern

We use a stack We use a stack SS to keep to keep track of the path track of the path between the start vertex between the start vertex and the current vertexand the current vertex

As soon as a back edge As soon as a back edge

((v, wv, w)) is encountered, we is encountered, we return the cycle as the return the cycle as the portion of the stack from portion of the stack from the top to vertex the top to vertex ww

Algorithm cycleDFS(G, v, z)setLabel(v, VISITED)S.push(v)for all e G.incidentEdges(v)

if getLabel(e) UNEXPLOREDw opposite(v,e)S.push(e)if getLabel(w) UNEXPLORED

setLabel(e, DISCOVERY)cycleDFS(G, w, z)S.pop(e)

elseT new empty stackrepeat

o S.pop()T.push(o)

until o wreturn T.elements()

S.pop(v)

Page 26: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2626

Breadth-First SearchBreadth-First SearchBreadth-first search Breadth-first search (BFS) is a general (BFS) is a general technique for technique for traversing a graphtraversing a graphA BFS traversal of a A BFS traversal of a graph G graph G – Visits all the vertices Visits all the vertices

and edges of Gand edges of G– Determines whether G Determines whether G

is connectedis connected– Computes the Computes the

connected connected components of Gcomponents of G

– Computes a spanning Computes a spanning forest of Gforest of G

BFS on a graph with BFS on a graph with nn vertices and vertices and mm edges edges takes takes OO((nnmm ) ) time time

BFS can be further BFS can be further extended to solve other extended to solve other graph problemsgraph problems– Find and report a path with Find and report a path with

the minimum number of the minimum number of edges between two given edges between two given vertices vertices

– Find a simple cycle, if there Find a simple cycle, if there is oneis one

Page 27: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2727

BFS AlgorithmBFS AlgorithmThe algorithm uses a The algorithm uses a mechanism for setting mechanism for setting and getting “labels” and getting “labels” of vertices and edgesof vertices and edges

Algorithm BFS(G, s)L0 new empty sequenceL0.insertLast(s)setLabel(s, VISITED)i 0 while Li.isEmpty()

Li 1 new empty sequence for all v Li.elements()

for all e G.incidentEdges(v) if getLabel(e) UNEXPLORED

w opposite(v,e)if getLabel(w)

UNEXPLOREDsetLabel(e, DISCOVERY)setLabel(w, VISITED)Li 1.insertLast(w)

elsesetLabel(e, CROSS)

i i 1

Algorithm BFS(G)Input graph GOutput labeling of the edges

and partition of the vertices of G

for all u G.vertices()setLabel(u, UNEXPLORED)

for all e G.edges()setLabel(e, UNEXPLORED)

for all v G.vertices()if getLabel(v)

UNEXPLORED

BFS(G, v)

Page 28: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2828

ExampleExample

CB

A

E

D

discovery edgecross edge

A visited vertex

A unexplored vertex

unexplored edge

L0

L1

F

CB

A

E

D

L0

L1

F

CB

A

E

D

L0

L1

F

Page 29: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 2929

Example (cont.)Example (cont.)

CB

A

E

D

L0

L1

F

CB

A

E

D

L0

L1

FL2

CB

A

E

D

L0

L1

FL2

CB

A

E

D

L0

L1

FL2

Page 30: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3030

Example (cont.)Example (cont.)

CB

A

E

D

L0

L1

FL2

CB

A

E

D

L0

L1

FL2

CB

A

E

D

L0

L1

FL2

Page 31: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3131

PropertiesPropertiesNotationNotation

GGss: connected component of : connected component of ss

Property 1Property 1BFSBFS((G, sG, s) ) visits all the vertices visits all the vertices and edges of and edges of GGss

Property 2Property 2The discovery edges labeled by The discovery edges labeled by BFSBFS((G, sG, s) ) form a spanning tree form a spanning tree TTss of of GGss

Property 3Property 3For each vertex For each vertex vv in in LLii

– The path of The path of TTss from from s s to to v v has has ii edges edges

– Every path from Every path from s s to to v v in in GGss has at has at least least ii edges edges

CB

A

E

D

L0

L1

FL2

CB

A

E

D

F

Page 32: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3232

AnalysisAnalysisSetting/getting a vertex/edge label takes Setting/getting a vertex/edge label takes OO(1)(1) time timeEach vertex is labeled twice Each vertex is labeled twice – once as UNEXPLOREDonce as UNEXPLORED– once as once as VISITEDVISITED

Each edge is labeled twiceEach edge is labeled twice– once as UNEXPLOREDonce as UNEXPLORED– once as once as DISCOVERYDISCOVERY or or CROSSCROSS

Each vertex is inserted once into a sequence Each vertex is inserted once into a sequence LLii Method incidentEdges is called once for each vertexMethod incidentEdges is called once for each vertexBFS runs in BFS runs in OO((n n m m)) time provided the graph is time provided the graph is represented by the adjacency list structurerepresented by the adjacency list structure– Recall that Recall that v v deg(deg(vv)) 22mm

Page 33: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3333

ApplicationsApplicationsUsing the template method pattern, we Using the template method pattern, we can specialize the BFS traversal of a graph can specialize the BFS traversal of a graph GG to solve the following problems in to solve the following problems in OO((n n mm)) time time– Compute the connected components of Compute the connected components of GG– Compute a spanning forest of Compute a spanning forest of GG– Find a simple cycle in Find a simple cycle in GG, or report that , or report that GG is a is a

forestforest– Given two vertices of Given two vertices of GG, find a path in , find a path in GG

between them with the minimum number of between them with the minimum number of edges, or report that no such path existsedges, or report that no such path exists

Page 34: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3434

DFS vs. BFSDFS vs. BFS

CB

A

E

D

L0

L1

FL2

CB

A

E

D

F

DFS BFS

ApplicationsApplications DFSDFS BFSBFS

Spanning forest, connected Spanning forest, connected components, paths, cyclescomponents, paths, cycles

Shortest pathsShortest paths

Biconnected componentsBiconnected components

Page 35: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3535

DFS vs. BFS (cont.)DFS vs. BFS (cont.)

Back edgeBack edge ((v,wv,w))– ww is an ancestor of is an ancestor of vv in in

the tree of discovery the tree of discovery edgesedges

Cross edgeCross edge ((v,wv,w))– ww is in the same level is in the same level

as as vv or in the next or in the next level in the tree of level in the tree of discovery edgesdiscovery edges

CB

A

E

D

L0

L1

FL2

CB

A

E

D

F

DFS BFS

Page 36: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3636

Digraphs Digraphs A A digraphdigraph is a is a graph whose edges graph whose edges are all directedare all directed– Short for “directed Short for “directed

graph”graph”

ApplicationsApplications– one-way streetsone-way streets– flightsflights– task schedulingtask scheduling A

C

E

B

D

Page 37: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3737

Digraph PropertiesDigraph Properties

A graph G=(V,E) such thatA graph G=(V,E) such that– Each edge goes in one direction:Each edge goes in one direction:

Edge Edge (a,b(a,b) goes ) goes from a to bfrom a to b, but , but not b to a.not b to a.

If G is simple, m If G is simple, m << n*(n-1). n*(n-1).

If we keep in-edges and out-If we keep in-edges and out-edges in separate adjacency edges in separate adjacency lists, we can perform listing of lists, we can perform listing of in-edges and out-edges in time in-edges and out-edges in time proportional to their size.proportional to their size.

A

C

E

B

D

Page 38: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3838

Digraph ApplicationDigraph ApplicationScheduling:Scheduling: edge edge (a,b(a,b) means task ) means task a must a must be completed before b can be startedbe completed before b can be started

The good life

ics141ics131 ics121

ics53 ics52ics51

ics23ics22ics21

ics161

ics151

ics171

Page 39: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 3939

Directed DFSDirected DFSWe can specialize the We can specialize the traversal algorithms (DFS traversal algorithms (DFS and BFS) to digraphs by and BFS) to digraphs by traversing edges only along traversing edges only along their directiontheir directionIn the directed DFS In the directed DFS algorithm, we have four algorithm, we have four types of edgestypes of edges– discovery edgesdiscovery edges– back edgesback edges– forward edgesforward edges– cross edgescross edges

A directed DFS starting a A directed DFS starting a vertex vertex ss determines the determines the vertices reachable from vertices reachable from ss

A

C

E

B

D

Page 40: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4040

ReachabilityReachabilityDFS DFS treetree rooted at v: vertices rooted at v: vertices reachable from v via directed pathsreachable from v via directed paths

A

C

E

B

D

F

A

C

E D

A

C

E

B

D

F

Page 41: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4141

Strong ConnectivityStrong Connectivity

Each vertex can reach all other verticesEach vertex can reach all other vertices

a

d

c

b

e

f

g

Page 42: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4242

Pick a vertex v in G.Pick a vertex v in G.

Perform a DFS from v in G.Perform a DFS from v in G.– If there’s a w not visited, print If there’s a w not visited, print

“no”.“no”.

Let G’ be G with edges Let G’ be G with edges reversed.reversed.

Perform a DFS from v in G’.Perform a DFS from v in G’.– If there’s a w not visited, print If there’s a w not visited, print

“no”.“no”.– Else, print “yes”.Else, print “yes”.

Running time: O(n+m).Running time: O(n+m).

Strong Connectivity AlgorithmStrong Connectivity Algorithm

G:

G’:

a

d

c

b

e

f

g

a

d

c

b

e

f

g

Page 43: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4343

Maximal subgraphs such that each vertex can Maximal subgraphs such that each vertex can reach all other vertices in the subgraphreach all other vertices in the subgraph

Can also be done in O(n+m) time using DFS, but Can also be done in O(n+m) time using DFS, but is more complicated (similar to biconnectivity).is more complicated (similar to biconnectivity).

Strongly Connected ComponentsStrongly Connected Components

{ a , c , g }

{ f , d , e , b }

a

d

c

b

e

f

g

Page 44: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4444

Transitive ClosureTransitive ClosureGiven a digraph Given a digraph GG, the , the transitive closure of transitive closure of GG is is the digraph the digraph G*G* such that such that– G*G* has the same has the same

vertices as vertices as GG– if if GG has a directed path has a directed path

from from uu to to v v ((u u v v), ), G*G* has a directed edge has a directed edge from from uu to to vv

The transitive closure The transitive closure provides reachability provides reachability information about a information about a digraphdigraph

B

A

D

C

E

B

A

D

C

E

G

G*

Page 45: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4545

Computing the Transitive ClosureComputing the Transitive ClosureWe can perform DFS starting at each We can perform DFS starting at each vertexvertex– O(n(n+m))O(n(n+m))

If there's a way to get from A to B and from B to C, then there's a way to get from A to C.

Alternatively ... Use dynamic programming: The Floyd-Warshall Algorithm

Page 46: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4646

Floyd-Warshall Transitive ClosureFloyd-Warshall Transitive ClosureIdea #1: Number the vertices 1, 2, …, n.Idea #1: Number the vertices 1, 2, …, n.

Idea #2: Consider paths that use only Idea #2: Consider paths that use only vertices numbered 1, 2, …, k, as vertices numbered 1, 2, …, k, as intermediate vertices:intermediate vertices:

k

j

i

Uses only verticesnumbered 1,…,k-1 Uses only vertices

numbered 1,…,k-1

Uses only vertices numbered 1,…,k(add this edge if it’s not already in)

Page 47: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4747

write c.s. program

play

Topological SortingTopological SortingNumber vertices, so that (u,v) in E implies Number vertices, so that (u,v) in E implies u < vu < v

wake up

eat

nap

study computer sci.

more c.s.

work out

sleep

dream about graphs

A typical student day1

2 3

4 5

6

7

8

9

1011

make cookies for professors

Page 48: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4848

Note: This algorithm is different than Note: This algorithm is different than the one in Goodrich-Tamassiathe one in Goodrich-Tamassia

Running time: O(n + m). How…?Running time: O(n + m). How…?

Algorithm for Topological SortingAlgorithm for Topological Sorting

Method TopologicalSort(G) H G // Temporary copy of G n G.numVertices() while H is not empty do

Let v be a vertex with no outgoing edgesLabel v nn n - 1Remove v from H

Page 49: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 4949

Topological Sorting Topological Sorting Algorithm using DFSAlgorithm using DFS

Simulate the algorithm by Simulate the algorithm by using depth-first searchusing depth-first search

O(n+m) time.O(n+m) time.

Algorithm topologicalDFS(G, v)Input graph G and a start vertex v of G Output labeling of the vertices of G

in the connected component of v setLabel(v, VISITED)for all e G.incidentEdges(v)

if getLabel(e) UNEXPLORED

w opposite(v,e)if getLabel(w)

UNEXPLOREDsetLabel(e, DISCOVERY)topologicalDFS(G, w)

else{e is a forward or cross edge}

Label v with topological number n n n - 1

Algorithm topologicalDFS(G)Input dag GOutput topological ordering of G

n G.numVertices()for all u G.vertices()

setLabel(u, UNEXPLORED)for all e G.edges()

setLabel(e, UNEXPLORED)for all v G.vertices()

if getLabel(v) UNEXPLORED

topologicalDFS(G, v)

Page 50: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5050

Topological Sorting ExampleTopological Sorting Example

Page 51: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5151

Topological Sorting ExampleTopological Sorting Example

9

Page 52: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5252

Topological Sorting ExampleTopological Sorting Example

8

9

Page 53: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5353

Topological Sorting ExampleTopological Sorting Example

78

9

Page 54: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5454

Topological Sorting ExampleTopological Sorting Example

78

6

9

Page 55: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5555

Topological Sorting ExampleTopological Sorting Example

78

56

9

Page 56: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5656

Topological Sorting ExampleTopological Sorting Example

7

4

8

56

9

Page 57: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5757

Topological Sorting ExampleTopological Sorting Example

7

4

8

56

3

9

Page 58: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5858

Topological Sorting ExampleTopological Sorting Example 2

7

4

8

56

3

9

Page 59: CSC311: Data Structures 1 Chapter 13: Graphs I Objectives: Graph ADT: Operations Graph Implementation: Data structures Graph Traversals: DFS and BFS Directed.

Graphs IGraphs I CSC311: Data StructuresCSC311: Data Structures 5959

Topological Sorting ExampleTopological Sorting Example 2

7

4

8

56

1

3

9