Sunteți pe pagina 1din 8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

Graphs
Objectives
Tolearnwhatagraphisandhowitisused.
Toimplementthegraphabstractdatatypeusingmultipleinternalrepresentations.
Toseehowgraphscanbeusedtosolveawidevarietyofproblems
Inthischapterwewillstudygraphs.Graphsareamoregeneralstructurethanthetreeswestudiedinthe
lastchapterinfactyoucanthinkofatreeasaspecialkindofgraph.Graphscanbeusedtorepresent
manyinterestingthingsaboutourworld,includingsystemsofroads,airlineflightsfromcitytocity,howthe
Internetisconnected,oreventhesequenceofclassesyoumusttaketocompleteamajorincomputer
science.Wewillseeinthischapterthatoncewehaveagoodrepresentationforaproblem,wecanuse
somestandardgraphalgorithmstosolvewhatotherwisemightseemtobeaverydifficultproblem.
Whileitisrelativelyeasyforhumanstolookataroadmapandunderstandtherelationshipsbetween
differentplaces,acomputerhasnosuchknowledge.However,wecanalsothinkofaroadmapasagraph.
Whenwedosowecanhaveourcomputerdointerestingthingsforus.Ifyouhaveeverusedoneofthe
Internetmapsites,youknowthatacomputercanfindtheshortest,quickest,oreasiestpathfromoneplace
toanother.
Asastudentofcomputerscienceyoumaywonderaboutthecoursesyoumusttakeinordertogetamajor.
Agraphisgoodwaytorepresenttheprerequisitesandotherinterdependenciesamongcourses.Figure1
showsanothergraph.Thisonerepresentsthecoursesandtheorderinwhichtheymustbetakento
completeamajorincomputerscienceatLutherCollege.

Figure1:PrerequisitesforaComputerScienceMajor

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

1/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

VocabularyandDefinitions
Nowthatwehavelookedatsomeexamplesofgraphs,wewillmoreformallydefineagraphandits
components.Wealreadyknowsomeofthesetermsfromourdiscussionoftrees.
Vertex
Avertex(alsocalledanode)isafundamentalpartofagraph.Itcanhaveaname,whichwewillcallthe
key.Avertexmayalsohaveadditionalinformation.Wewillcallthisadditionalinformationthepayload.
Edge
Anedge(alsocalledanarc)isanotherfundamentalpartofagraph.Anedgeconnectstwoverticesto
showthatthereisarelationshipbetweenthem.Edgesmaybeonewayortwoway.Iftheedgesinagraph
arealloneway,wesaythatthegraphisadirectedgraph,oradigraph.Theclassprerequisitesgraph
shownaboveisclearlyadigraphsinceyoumusttakesomeclassesbeforeothers.
Weight
Edgesmaybeweightedtoshowthatthereisacosttogofromonevertextoanother.Forexampleina
graphofroadsthatconnectonecitytoanother,theweightontheedgemightrepresentthedistance
betweenthetwocities.
Withthosedefinitionsinhandwecanformallydefineagraph.AgraphcanberepresentedbyG where
G = (V , E) .ForthegraphG ,V isasetofverticesandE isasetofedges.Eachedgeisatuple(v, w)
wherew, v V .Wecanaddathirdcomponenttotheedgetupletorepresentaweight.Asubgraphs isa
setofedgeseandverticesv suchthate Eandv V .
Figure2showsanotherexampleofasimpleweighteddigraph.Formallywecanrepresentthisgraphas
thesetofsixvertices:
V =

{V 0, V 1, V 2, V 3, V 4, V 5}

andthesetofnineedges:
(v0, v1, 5), (v1, v2, 4), (v2, v3, 9), (v3, v4, 7), (v4, v0, 1),
E =

}
(v0, v5, 2), (v5, v4, 8), (v3, v5, 3), (v5, v2, 1)

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

2/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

Figure2:ASimpleExampleofaDirectedGraph
TheexamplegraphinFigure2helpsillustratetwootherkeygraphterms:
Path
Apathinagraphisasequenceofverticesthatareconnectedbyedges.Formallywewoulddefineapath
asw 1 , w 2 , . . . , w n suchthat(w i , w i+1 ) E forall1 i n 1 .Theunweightedpathlengthisthe
numberofedgesinthepath,specificallyn 1 .Theweightedpathlengthisthesumoftheweightsofall
theedgesinthepath.ForexampleinFigure2thepathfromV 3 toV 1 isthesequenceofvertices
(V 3, V 4, V 0, V 1).Theedgesare{(v3, v4, 7), (v4, v0, 1), (v0, v1, 5)} .
Cycle
Acycleinadirectedgraphisapaththatstartsandendsatthesamevertex.Forexample,inFigure2the
path(V 5, V 2, V 3, V 5)isacycle.Agraphwithnocyclesiscalledanacyclicgraph.Adirectedgraph
withnocyclesiscalledadirectedacyclicgraphoraDAG.Wewillseethatwecansolveseveral
importantproblemsiftheproblemcanberepresentedasaDAG.

TheGraphAbstractDataType
Thegraphabstractdatatype(ADT)isdefinedasfollows:
Graph()createsanew,emptygraph.
addVertex(vert)addsaninstanceof Vertextothegraph.
addEdge(fromVert,toVert)Addsanew,directededgetothegraphthatconnectstwovertices.
addEdge(fromVert,toVert,weight)Addsanew,weighted,directededgetothegraphthat

connectstwovertices.

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

3/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

getVertex(vertKey)findsthevertexinthegraphnamed vertKey.
getVertices()returnsthelistofallverticesinthegraph.
inreturns Trueforastatementoftheform vertexingraph,ifthegivenvertexisinthegraph,
Falseotherwise.

BeginningwiththeformaldefinitionforagraphthereareseveralwayswecanimplementthegraphADTin
Python.WewillseethattherearetradeoffsinusingdifferentrepresentationstoimplementtheADT
describedabove.Therearetwowellknownimplementationsofagraph,theadjacencymatrixandthe
adjacencylist.Wewillexplainbothoftheseoptions,andthenimplementoneasaPythonclass.

AnAdjacencyMatrix
Oneoftheeasiestwaystoimplementagraphistouseatwodimensionalmatrix.Inthismatrix
implementation,eachoftherowsandcolumnsrepresentavertexinthegraph.Thevaluethatisstoredin
thecellattheintersectionofrowv andcolumnw indicatesifthereisanedgefromvertexv tovertexw .
Whentwoverticesareconnectedbyanedge,wesaythattheyareadjacent.Figure3illustratesthe
adjacencymatrixforthegraphinFigure2.Avalueinacellrepresentstheweightoftheedgefromvertexv
tovertexw .

Figure3:AnAdjacencyMatrixRepresentationforaGraph
Theadvantageoftheadjacencymatrixisthatitissimple,andforsmallgraphsitiseasytoseewhich
nodesareconnectedtoothernodes.However,noticethatmostofthecellsinthematrixareempty.
Becausemostofthecellsareemptywesaythatthismatrixissparse.Amatrixisnotaveryefficientway
tostoresparsedata.Infact,inPythonyoumustgooutofyourwaytoevencreateamatrixstructurelike
theoneinFigure3.

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

4/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

Theadjacencymatrixisagoodimplementationforagraphwhenthenumberofedgesislarge.Butwhatdo
wemeanbylarge?Howmanyedgeswouldbeneededtofillthematrix?Sincethereisonerowandone
2

columnforeveryvertexinthegraph,thenumberofedgesrequiredtofillthematrixis|V | .Amatrixisfull
wheneveryvertexisconnectedtoeveryothervertex.Therearefewrealproblemsthatapproachthissort
ofconnectivity.Theproblemswewilllookatinthischapterallinvolvegraphsthataresparselyconnected.

AnAdjacencyList
Amorespaceefficientwaytoimplementasparselyconnectedgraphistouseanadjacencylist.Inan
adjacencylistimplementationwekeepamasterlistofalltheverticesintheGraphobjectandtheneach
vertexobjectinthegraphmaintainsalistoftheotherverticesthatitisconnectedto.Inourimplementation
ofthe Vertexclasswewilluseadictionaryratherthanalistwherethedictionarykeysarethevertices,
andthevaluesaretheweights.Figure4illustratestheadjacencylistrepresentationforthegraphinFigure
2.

Figure4:AnAdjacencyListRepresentationofaGraph

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

5/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

Theadvantageoftheadjacencylistimplementationisthatitallowsustocompactlyrepresentasparse
graph.Theadjacencylistalsoallowsustoeasilyfindallthelinksthataredirectlyconnectedtoaparticular
vertex.

Implementation
Usingdictionaries,itiseasytoimplementtheadjacencylistinPython.InourimplementationoftheGraph
abstractdatatypewewillcreatetwoclasses(seeListing1andListing2), Graph,whichholdsthemaster
listofvertices,and Vertex,whichwillrepresenteachvertexinthegraph.
Each Vertexusesadictionarytokeeptrackoftheverticestowhichitisconnected,andtheweightof
eachedge.Thisdictionaryiscalled connectedTo.Thelistingbelowshowsthecodeforthe Vertexclass.
Theconstructorsimplyinitializesthe id,whichwilltypicallybeastring,andthe connectedTodictionary.
The addNeighbormethodisusedaddaconnectionfromthisvertextoanother.The getConnections
methodreturnsalloftheverticesintheadjacencylist,asrepresentedbythe connectedToinstance
variable.The getWeightmethodreturnstheweightoftheedgefromthisvertextothevertexpassedasa
parameter.
Listing1
classVertex:
def__init__(self,key):
self.id=key
self.connectedTo={}
defaddNeighbor(self,nbr,weight=0):
self.connectedTo[nbr]=weight
def__str__(self):
returnstr(self.id)+'connectedTo:'+str([x.idforxinself.connected
To])
defgetConnections(self):
returnself.connectedTo.keys()
defgetId(self):
returnself.id
defgetWeight(self,nbr):
returnself.connectedTo[nbr]

The Graphclass,showninthenextlisting,containsadictionarythatmapsvertexnamestovertexobjects.
InFigure4thisdictionaryobjectisrepresentedbytheshadedgraybox. Graphalsoprovidesmethodsfor
addingverticestoagraphandconnectingonevertextoanother.The getVerticesmethodreturnsthe
namesofalloftheverticesinthegraph.Inaddition,wehaveimplementedthe __iter__methodtomake
iteasytoiterateoverallthevertexobjectsinaparticulargraph.Together,thetwomethodsallowyouto
iterateovertheverticesinagraphbyname,orbytheobjectsthemselves.

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

6/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

Listing2
classGraph:
def__init__(self):
self.vertList={}
self.numVertices=0
defaddVertex(self,key):
self.numVertices=self.numVertices+1
newVertex=Vertex(key)
self.vertList[key]=newVertex
returnnewVertex
defgetVertex(self,n):
ifninself.vertList:
returnself.vertList[n]
else:
returnNone
def__contains__(self,n):
returnninself.vertList
defaddEdge(self,f,t,cost=0):
iffnotinself.vertList:
nv=self.addVertex(f)
iftnotinself.vertList:
nv=self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t],cost)
defgetVertices(self):
returnself.vertList.keys()
def__iter__(self):
returniter(self.vertList.values())

Usingthe Graphand Vertexclassesjustdefined,thefollowingPythonsessioncreatesthegraphin


Figure2.Firstwecreatesixverticesnumbered0through5.Thenwedisplaythevertexdictionary.Notice
thatforeachkey0through5wehavecreatedaninstanceofa Vertex.Next,weaddtheedgesthat
connecttheverticestogether.Finally,anestedloopverifiesthateachedgeinthegraphisproperlystored.
YoushouldchecktheoutputoftheedgelistattheendofthissessionagainstFigure2.

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

7/8

1/5/2015

Graphs Problem Solving with Algorithms and Data Structures

>>>g=Graph()
>>>foriinrange(6):
...g.addVertex(i)
>>>g.vertList
{0:<adjGraph.Vertexinstanceat0x41e18>,
1:<adjGraph.Vertexinstanceat0x7f2b0>,
2:<adjGraph.Vertexinstanceat0x7f288>,
3:<adjGraph.Vertexinstanceat0x7f350>,
4:<adjGraph.Vertexinstanceat0x7f328>,
5:<adjGraph.Vertexinstanceat0x7f300>}
>>>g.addEdge(0,1,5)
>>>g.addEdge(0,5,2)
>>>g.addEdge(1,2,4)
>>>g.addEdge(2,3,9)
>>>g.addEdge(3,4,7)
>>>g.addEdge(3,5,3)
>>>g.addEdge(4,0,1)
>>>g.addEdge(5,4,8)
>>>g.addEdge(5,2,1)
>>>forving:
...forwinv.getConnections():
...print("(%s,%s)"%(v.getId(),w.getId()))
...
(0,5)
(0,1)
(1,2)
(2,3)
(3,4)
(3,5)
(4,0)
(5,4)
(5,2)

Copyright2013BradMiller,DavidRanum.Createdusing
Sphinx(http://sphinx.pocoo.org/)1.1.3.

29readersonlinenow|Notloggedin|Backtotop

http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html

8/8

S-ar putea să vă placă și