Upload
lydieu
View
218
Download
1
Embed Size (px)
Citation preview
Chapter8:Graphs
IntroductoryRemarks
• Althoughtreesarequiteflexible,theyhaveaninherentlimitationinthattheycanonlyexpresshierarchicalstructures
• Fortunately,wecangeneralizeatreetoformagraph,inwhichthislimitationisremoved
• Informally,agraphisacollectionofnodesandtheconnectionsbetweenthem
• Figure8.1illustratessomeexamplesofgraphs;noticethereistypicallynolimitationonthenumberofverticesoredges
• Consequently,graphsareextremelyversatileandapplicabletoawidevarietyofsituations
• Graphtheoryhasdevelopedintoasophisticatedfieldofstudysinceitsoriginsintheearly1700s
Data Structures and Algorithms in C++, Fourth Edition 2
IntroductoryRemarks(continued)
Fig.8.1Examplesofgraphs:(a–d)simplegraphs;(c)acompletegraphK4;(e)amultigraph;(f)apseudograph;(g)acircuitinadigraph;(h)acycleinthedigraph
Data Structures and Algorithms in C++, Fourth Edition 3
IntroductoryRemarks(continued)
• And,whilemanyresultsaretheoretical,theapplicationsofgraphsarenumerousandworthconsideration
• First,though,weneedtoconsidersomedefinitions• Asimplegraph G =(V,E)consistsofa(finite)setdenotedby
V,andacollectionE,ofunorderedpairs{u,v}ofdistinctelementsfromV
• EachelementofV iscalledavertex orapoint oranode,andeachelementofE iscalledanedge oraline oralink
• Thenumberofvertices,the cardinality ofV,iscalledtheorderofgraph anddevotedby|V|
• ThecardinalityofE,calledthesizeofgraph,isdenotedby|E|
Data Structures and Algorithms in C++, Fourth Edition 4
IntroductoryRemarks(continued)
• AgraphG =(V,E)isdirected iftheedgesetiscomposedoforderedvertex(node)pairs
• Nowthesedefinitionsrestrictthenumberofedgesthatcanoccurbetweenanytwoverticestoone
• Ifweallowmultipleedgesbetweenanytwovertices,wehaveamultigraph (Figure8.1e)
• Formally,amultigraphisdefinedasG(V,E,f)whereV isthesetofvertices,E theedges,andf:E→{{vi,vj}:vi,vj ∈Vandvi ≠vj}isafunctiondefiningedgesaspairsofdistinctvertices
• Apseudograph isamultigraphthatdropsthevi ≠vjcondition,allowingthegraphtohaveloops(Figure8.1f)
Data Structures and Algorithms in C++, Fourth Edition 5
IntroductoryRemarks(continued)
• Apath betweenverticesv1 andvn isasequenceofedgesdenotedv1,v2,…,vn-1,vn
• Ifv1 =vn,andtheedgesdon’trepeat,itisacircuit (Figure8.1g);iftheverticesinacircuitaredifferent,itisacycle(Figure8.1h)
• Aweightedgraph assignsavaluetoeachedge,basedoncontextualusage
• Acomplete graphofn vertices,denotedKn,hasexactlyoneedgebetweeneachpairofvertices(Figure8.1c)
• Theedgecount E = 𝑉2 = $ !
&! $ '& ! =$ $ ')
& =O 𝑉 2
Data Structures and Algorithms in C++, Fourth Edition 6
IntroductoryRemarks(continued)
• Asubgraph ofagraphG,designatedG’,isthegraph(V’,E’)whereV’⊆ V andE’⊆ E
• Iftheedgesofthesubgrapharedefinedsuchthate ∈ E ife ∈E’,thenthesubgraphissaidtobeinduced onitsverticesV’
• Twoverticesareadjacent iftheedgedefinedbythemisinE• Thatedgeiscalledincidentwith thevertices• Thenumberofedgesincidentwithavertexv,isthedegree
ofthevertex;ifthedegreeis0,v iscalledisolated• NoticethatthedefinitionofagraphallowsthesetE tobe
empty,soagraphmaybecomposedofisolatedvertices
Data Structures and Algorithms in C++, Fourth Edition 7
GraphRepresentation• Graphscanberepresentedinanumberofways• Oneofthesimplestisanadjacencylist,whereeachvertex
adjacenttoagivevertexislisted• Thiscanbedesignedasatable(knownasastar
representation)oralinkedlist,showninFigure8.2b-conpage393
• Anotherrepresentationisasamatrix,whichcanbedesignedintwoways
• Anadjacencymatrix isa|V|x|V|binarymatrixwhere:
8Data Structures and Algorithms in C++, Fourth Edition
( )1 ifthereexistsanedge
0 otherwisei j
ij
v va
ìï= íïî
9Data Structures and Algorithms in C++, Fourth Edition
GraphRepresentation(continued)• AnexampleofanadjacencymatrixisshowninFigure8.2d• Theorderoftheverticesinthematrixisarbitrary,sothere
aren!possiblematricesforagraphofn vertices• Itisalsopossibletogeneralizeanadjacencymatrixdefinition
tohandleamultigraphbydefiningaij =numberofedgesbetweenvi andvj
• Asecondmatrixrepresentationisbasedonincidences,hencethenameincidencematrix
• Anincidencematrix isa|V|x|E|binarymatrixwhere:
10Data Structures and Algorithms in C++, Fourth Edition
1 edgee isincidentwithvertex0 otherwise
j iij
va
ì= íî
GraphRepresentation(continued)• AnexampleofanincidencematrixisshowninFigure8.2e• Foramultigraph,manycolumnsarethesame,andacolumn
withasingle1representsaloop• Asfarasusage,theproperstructuredependstoagreat
extentonthekindsofoperationsthatneedtobedone
11Data Structures and Algorithms in C++, Fourth Edition
GraphTraversals
• Liketreetraversals,graphtraversalsvisiteachnodeonce• However,wecannotapplytreetraversalalgorithmstographs
becauseofcyclesandisolatedvertices• Onealgorithmforgraphtraversal,calledthedepth-first
search,wasdevelopedbyJohnHopcroftandRobertTarjanin1974
• Inthisalgorithm,eachvertexisvisitedandthenalltheunvisitedverticesadjacenttothatvertexarevisited
• Ifthevertexhasnoadjacentvertices,oriftheyhaveallbeenvisited,webacktracktothatvertex’spredecessor
• Thiscontinuesuntilwereturntothevertexwherethetraversalstarted
Data Structures and Algorithms in C++, Fourth Edition 12
GraphTraversals(continued)
• Ifanyverticesremainunvisitedatthispoint,thetraversalrestartsatoneoftheunvisitedvertices
• Althoughnotnecessary,thealgorithmassignsuniquenumberstothevertices,sotheyarerenumbered
• Pseudocodeforthisalgorithmisshownonpage395• Figure8.3showsanexampleofthistraversal;thenumbers
indicatetheorderinwhichthenodesarevisited;thesolidlinesindicatetheedgestraversedduringthesearch
Fig.8.3AnexampleofapplicationofthedepthFirstSearch()algorithmtoagraph
Data Structures and Algorithms in C++, Fourth Edition 13
Depth-First-SearchDFS(v)
num(v)= i++;
for all vertices u adjrcent to v
if num(u) is 0
attchedge(uv) to edges;
DFS(u);depthFirstSearch()
for all vertices v
num(v)=0;
edges = null;
i=1;while there is a vertex v such num(v) is 0
DFS(v);
output edges;
Data Structures and Algorithms in C++, Fourth Edition 14
GraphTraversals(continued)
• Thealgorithmguaranteesthatwewillcreateatree(oraforest,whichisasetoftrees)includingthegraph’svertices
• Suchatreeiscalledaspanningtree• Theguaranteeisbasedonthealgorithmnotprocessingany
edgethatleadstoanalreadyvisitednode• Consequently,someedgesarenotincludedinthetree
(markedwithdashedlines)• Theedgesincludedinthetreearecalledforwardedges;
thoseomittedarecalledbackedges• InFigure8.4,wecanseethisalgorithmappliedtoadigraph,
whichisagraphwheretheedgeshaveadirection
Data Structures and Algorithms in C++, Fourth Edition 15
GraphTraversals(continued)
Fig.8.4ThedepthFirstSearch()algorithmappliedtoadigraph
• Noticeinthiscaseweendupwithaforestofthreetrees,becausethetraversalmustfollowthedirectionoftheedges
• Thereareanumberofalgorithmsbasedondepth-firstsearching
• However,somearemoreefficientiftheunderlyingmechanismisbreadth-firstinstead
Data Structures and Algorithms in C++, Fourth Edition 16
GraphTraversals(continued)
• Recallfromourconsiderationoftreetraversalsthatdepth-firsttraversalsusedastack,whilebreadth-firstusedqueues
• Thiscanbeextendedtographs,asthepseudocodeonpage397illustrates
• Figure8.4showsthisappliedtoagraph;Figure8.5showstheapplicationtoadigraph
• Inboth,thebasicoperationistomarkall theverticesaccessiblefromagivenvertex,placingtheminaqueueastheyarevisited
• Thefirstvertexinthequeueisthenremoved,andtheprocessrepeated
• Novisitednodesarerevisited;ifanodehasnoaccessiblenodes,thenextnodeinthequeueisremovedandprocessed
Data Structures and Algorithms in C++, Fourth Edition 17
Breath-First-searchbreathFirstSearch()for all vertices unum(u) = 0;
edges = null;i = 1;while there is a vertex v such that num(v) is 0num(v) = i++;enqueue(v);while queue is not emptyv = dequeue();for all vertices u adjacent to vif num(u) is 0num(u) = i++;enqueue(u);addedge(vu) to edges;
output edges; Data Structures and Algorithms in C++, Fourth Edition 18
GraphTraversals(continued)
Fig.8.5AnexampleofapplicationofthebreadthFirstSearch()algorithmtoagraph
Fig.8.6ThebreadthFirstSearch()algorithmappliedtoadigraph
Data Structures and Algorithms in C++, Fourth Edition 19
ShortestPaths• Aclassicalproblemingraphtheoryisfindingtheshortestpath
betweentwonodes,withnumerousapproachessuggested• Theedgesofthegraphareassociatedwithvaluesdenoting
suchthingsasdistance,time,costs,amounts,etc.• Ifwe’redeterminingthedistancebetweentwovertices,sayv
andu,informationaboutthedistancebetweentheintermediateverticesinthepath,w,needstobekepttrackof
• Thiscanberecordedasalabelassociatedwiththevertices• Thelabelmaysimplybethedistancebetweenvertices,orthe
distancealongwiththecurrentnode’spredecessorinthepath
• Methodsforfindingshortestpathsdependontheselabels
Data Structures and Algorithms in C++, Fourth Edition 20
ShortestPaths(continued)• Basedonhowmanytimesthelabelsareupdated,solutionsto
theshortestpathproblemfallintotwogroups• Inlabel-settingmethods,onevertexisassignedavaluethat
remainsunchanged• Thisoccurseachtimewegothroughtheverticesthatremain
tobeprocessed• Themaindrawbacktothisisthatwecannotprocessgraphs
thathavenegativeweightsonanyedges• Inlabel-correctingmethods,anylabelcanbechanged• Thismeansitcanbeappliedtographswithnegativeweights
aslongastheydon’thavenegativecycles(acyclewherethesumoftheedgesisanegativevalue)
Data Structures and Algorithms in C++, Fourth Edition 21
ShortestPaths(continued)• Howeverthismethodguaranteesthatafterprocessingis
complete,forallverticesthecurrentdistancesindicatetheshortestpath
• Mostoftheseforms(bothlabel-settingandlabel-correcting)canbelookedataspartofthesamegeneralprocess,however
• Thatisthetaskoffindingtheshortestpathsfromonevertextoalltheothervertices,thepseudocodebeingonpage399
• Inthisalgorithm,alabelisdefinedas:label(v) = (currDist(v),predecessor(v))
• TwoopenissuesinthecodearethedesignofthesetcalledtoBeChecked andtheordernewvaluesareassignedtov
• Itisthedesignofthesetthatimpactsboththechoiceofvandtheefficiencyofthealgorithm
Data Structures and Algorithms in C++, Fourth Edition 22
23Data Structures and Algorithms in C++, Fourth Edition
ShortestPaths(continued)• Thedistinctionbetweenlabel-settingandlabel-correcting
algorithmsisthewaythevalueforvertexv ischosen• ThisisthevertexinthesettoBeChecked withthesmallest
currentdistance• Inconsideringlabel-settingalgorithms,oneofthefirstwas
developedbyEdsgarDijkstrain1956• Inthisalgorithm,theshortestfromamonganumberofpaths
fromavertex,v,aretried• Thismeansthataparticularpathmaybeextendedbyadding
onemoreedgetoiteachtimev ischecked• However,ifthepathislongerthananyotherpathfromthat
point,itisdropped,andtheotherpathisexpanded
Data Structures and Algorithms in C++, Fourth Edition 24
ShortestPaths(continued)• Sincetheverticesmayhavemorethanoneoutgoingedge,
eachnewedgeaddspossiblepathsforexploration• Thuseachvertexisvisited,thenewpathsarestarted,andthe
vertexisthennotusedanymore• Oncealltheverticesarevisited,thealgorithmisdone• Dijkstra’salgorithmisshownonpage400;itisderivedfrom
thegeneralalgorithmbychangingthelinev=a vertex in toBeChecked;
tov=a vertex in toBeChecked with minimal currDist(v);
• Italsoextendstheconditionintheif tomakepermanentthecurrentdistanceofverticeseliminatedfromtheset
Data Structures and Algorithms in C++, Fourth Edition 25
ShortestPaths(continued)• Noticethattheset’sstructureisnotindicated;recallitisthe
structurethatdeterminesefficiency• Figure8.7illustratesthisforthegraphinpart(a)
Fig.8.7AnexecutionofDijkstraAlgorithm()
Data Structures and Algorithms in C++, Fourth Edition 26
ShortestPaths(continued)• Asalabel-settingalgorithm,Dijkstra’sapproachmayfailwhen
negativeweightsareusedingraphs• Todealwiththat,alabel-correctingalgorithmisneeded• Oneofthefirstlabel-correctingalgorithmswasdevelopedby
LesterR.Ford,Jr.inthelate1950s• ItusesthesametechniqueasDijkstra’smethodtosetthe
currentdistances,butpostponesdeterminingtheshortestdistanceforanyvertexuntiltheentiregraphisprocessed
• Whileitiscapableofhandlinggraphswithnegativeweights,itcannotdealwithnegativecycles
• Inthealgorithm,alledgesarewatchedinanattempttofindanimprovementforthecurrentdistanceofthevertices
Data Structures and Algorithms in C++, Fourth Edition 27
ShortestPaths(continued)• Thepseudocodeforthealgorithmisshownonpage402• Tofacilitatemonitoringthevertices,analphabeticsequence
canbeused• Thatwaythealgorithmcangothroughthelistrepeatedlyand
adjustanyvertex’scurrentdistanceasneeded• Figure8.8containsanexampleofthis;notethatthegraph
doesincludenegativelyweightededges• Whileavertexmaychangeitscurrentdistanceduringthe
sameiteration,whendoneeachvertexcanbereachedbytheshortestpathfromthestartingvertex
Data Structures and Algorithms in C++, Fourth Edition 28
ShortestPaths(continued)
Data Structures and Algorithms in C++, Fourth Edition 29
Fig.8.8FordAlgorithm()appliedtoadigraphwithnegativeweights
• InthecaseofDijkstra’salgorithm,weobservedthattheefficiencycanbeimprovedbythechoiceofdatastructure
• Thisinturnimpactsthewaytheedgesandverticesarescanned
ShortestPaths(continued)• Thisobservationalsoholdsforlabel-correctingalgorithms;in
particular,theFordAlgorithm()specifiesnoorderforedgechecking
• IntheexampleofFigure8.8,theapproachwastovisitalladjacencylistsofallverticesineachiteration
• Howeverthisrequiresthatalltheedgesarecheckedeverytime,whichisinefficient
• Amoresensibleorganizationoftheverticescanreducethenumberofvisitspervertex
• Thegenericalgorithmonpage399suggestsanimprovementbyexplicitlyaccessingtoBeChecked
• IntheFordAlgorithm()thisstructureisusedimplicitly,andthenonlyasthesetofallvertices
Data Structures and Algorithms in C++, Fourth Edition 30
ShortestPaths(continued)• Sobasedonthis,wecanderiveagenerallabel-correcting
algorithm,showninpseudocodeonpage403• Asindicatedbefore,theefficiencyofthealgorithmdepends
directlyonthedatastructureusedfortoBeChecked• Onepossibilityisaqueue,andwasthebasisforoneofthe
earliestimplementations• Withaqueue,asavertex,v isremoved,thecurrentdistance
toitsneighborsischecked• Ifanyofthosedistancesisupdated,thevertexwhose
distancewaschangedisaddedtothequeue• Whilestraightforward,itcansometimesreevaluatethesame
labelsexcessively
Data Structures and Algorithms in C++, Fourth Edition 31
ShortestPaths(continued)• Figure8.9illustratesthisproblemforthegraphofFigure8.8a
Fig.8.9AnexecutionoflabelCorrectingAlgorithm(),whichusesaqueue
• Ascanbeseen,anumberofverticesareupdatedmultipletimes
Data Structures and Algorithms in C++, Fourth Edition 32
ShortestPaths(continued)• Toavoidthissituation,adequecanbeusedinplaceofthe
queue• Inthisapproach,verticesneedingtobecheckedforthefirst
timeareaddedattheend,otherwisetheyareplacedinfront• Thereasoningbehindthisisthatifagivenvertex,v,is
includedforthefirsttime,theverticesaccessiblefromithaveyettobeprocessed,sotheywillbeprocessedafterv
• However,ifv hasbeenprocessed,thoseverticesarelikelystillinthelistawaitingprocessing,soputtingv infrontmayavoidunnecessaryupdates
• Figure8.10showstheresultofusingadequeinsteadofaqueue
Data Structures and Algorithms in C++, Fourth Edition 33
ShortestPaths(continued)
Fig.8.10AnexecutionoflabelCorrectingAlgorithm(),whichappliesadeque
• Theuseofadequedoessufferfromoneproblem,however• Itsworstcaseperformanceisexponentialinthenumberof
vertices
Data Structures and Algorithms in C++, Fourth Edition 34
ShortestPaths(continued)• However,theaveragecaseisabout60%betterthanthe
queueversionofthesamealgorithm• Avariationofthisapproachusestwoqueuesseparately,
ratherthancombinedinadeque• Inthisvariation,verticesenqueuedforthefirsttimeare
placedinthefirstqueue;otherwisetheyareplacedinthesecond
• Verticesarethendequeuedfromthefirstqueueifitisnotempty;otherwisetheyaretakenfromthesecond
• Thethresholdalgorithm isanothervariationofthelabel-correctingmethodthatusestwolists
• Verticesareremovedfromthefirstlistforprocessing
Data Structures and Algorithms in C++, Fourth Edition 35
ShortestPaths(continued)• Avertexwillbeaddedtotheendofthefirstlistifthevalueof
itslabelisbelowthethresholdlevel• Otherwiseitwillbeaddedtothesecondlist• Ifthefirstlistbecomesempty,thethresholdismodifiedtoa
valuegreaterthantheminimumlabelvalueofallverticesinthesecondlist
• Thenthoseverticeswhoselabelsarelessthanthenewthresholdaremovedfromthesecondlisttothefirstlist
• Yetanotherapproachisthesmalllabelfirstmethod• Inthismethod,avertexisplacedatthefrontofthedequeif
itslabelissmallerthanthelabelofthecurrentfrontofthedeque;otherwiseitisplacedattherear
Data Structures and Algorithms in C++, Fourth Edition 36
ShortestPaths(continued)• All-to-AllShortestPathProblem
– Giventheissuesoffindingtheshortestpathfromonevertextoanother,theproblemoffindingallshortestpathsbetweentwoverticesmightseemdaunting
– However,amethoddevelopedbyStephenWarshallin1962doesitfairlyeasily,aslongasanadjacencymatrixthatprovidesedgeweightsisavailable
– Thistechniquecanalsohandlenegativeedgeweightsandthealgorithmisshownonpage406
– Anexampleofthealgorithm’sapplication,togetherwiththeaccompanyingadjacencymatrix,isshowninFigure8.11onpage407
– Thealgorithmcanalsodetectcyclesifthediagonalofthematrixisinitializedto∞insteadof0
– Ifanyofthediagonalvaluesgetchanged,thegraphcontainsacycle
Data Structures and Algorithms in C++, Fourth Edition 37
ShortestPaths(continued)• All-to-AllShortestPathProblem (continued)
– Asitturnsout,ifaninitialvalueof∞isnotchangedduringprocessing,thenonevertexcannotreachtheother
– Thealgorithm’ssimplicityisreflectedinthedeterminationofitscomplexity;therearethreeloopsexecuted 𝑉 timessoitisO 𝑉 3
– Thisisadequatefordense,near-completegraphs,butiftheyaresparse,itmaybebettertouseaone-to-allmethodappliedtoeachvertex
– Generallythisshouldbealabel-settingalgorithm,butrecallthatthesetypesofroutinescannothandlenegativeedgeweights
– Fortunately,therearetransformationsavailablethateliminatethenegativeweightswhilepreservingtheshortestpathsoftheoriginal
Data Structures and Algorithms in C++, Fourth Edition 38
CycleDetection
• Numerousalgorithmsrelyontheirabilitytodetectcyclesingraphs
• OurconsiderationoftheWarshall-Floydalgorithminthepreviousexampledemonstratedthatitcandetectcycles
• However,itscubicordermakesittooinefficienttouseinallcircumstances,soothermethodshavetobeconsidered
• Onealgorithm,basedonthedepthFirstSearch()routine,workswellforundirectedgraphs
• Thepseudocodeforthisisshownonpage408
Data Structures and Algorithms in C++, Fourth Edition 39
CycleDetection
Data Structures and Algorithms in C++, Fourth Edition 40
SpanningTrees• Consideranairlinethathasroutesbetweensevencities
representedasthegraphinFigure8.14a
Fig.8.14Agraphrepresenting(a)theairlineconnectionsbetweensevencitiesand(b–d)threepossiblesetsofconnections
• Ifeconomichardshipsforcetheairlinetocutroutes,whichonesshouldbekepttopreservearoutetoeachcity,ifonlyindirectly?
• OnepossibilityisshowninFigure8.14b
Data Structures and Algorithms in C++, Fourth Edition 41
SpanningTrees(continued)• However,wewanttomakesurewehavetheminimum
connectionsnecessarytopreservetheroutes• Toaccomplishthis,aspanningtreeshouldbeused,
specificallyonecreatedusingdepthFirstSearch()• Thereisapossibilityofmultiplespanningtrees(Figure8.14c-
d),buteachofthesehastheminimumnumberofedges• Wedon’tknowwhichofthesemightbeoptimal,sincewe
haven’ttakendistancesintoaccount• Theairline,wantingtominimizecosts,willwanttousethe
shortestdistancesfortheconnections• Sowhatwewanttofindistheminimumspanningtree,
wherethesumoftheedgeweightsisminimal
Data Structures and Algorithms in C++, Fourth Edition 42
SpanningTrees(continued)• Theproblemwelookedatearlierinvolvingfindingaspanning
treeinasimplegraphisacaseofthiswhereedgeweights=1• Soeachspanningtreeisaminimumtreeinasimplegraph• Thereareanumberofsolutionstotheminimumspanning
treeproblem,andwewillconsidertwo• OnepopularalgorithmisKruskal’salgorithm,developedby
JosephKruskalin1956• Itorderstheedgesbyweight,andthencheckstoseeifthey
canbeaddedtothetreeunderconstruction• Itwillbeaddedifitsinclusiondoesn’tcreateacycle
Data Structures and Algorithms in C++, Fourth Edition 43
SpanningTrees(continued)• Thealgorithmisasfollows:KruskalAlgorithm(weighted connected undirected graph)
tree = null;
edges = sequence of all edges of graph sorted by weight;
for (i = 1; i ≤ |E| and |tree| < |V| – 1; i++)
if ei from edges does not form a cycle with edges in tree
add ei to tree;
• Astep-by-stepexampleoftheapplicationofthisalgorithmisshowninFigure8-15ba-bfonpage413
• Itisnotnecessarytoordertheedgesinordertobuildaspanningtree,anyorderofedgescanbeused
• AnalgorithmdevelopedbyDijkstrain1960(andindependentlybyRobertKalaba)pursuesthisapproach
Data Structures and Algorithms in C++, Fourth Edition 44
SpanningTrees(continued)
Data Structures and Algorithms in C++, Fourth Edition 45
SpanningTrees(continued)• Thisalgorithmisshownbelow:DijkstraMethod(weighted connected undirected graph)
tree = null;
edges = an unsorted sequence of all edges of graph;
for i = 1 to |E|
add ei to tree;
if there is a cycle in tree
remove an edge with maximum weight from this only cycle;
• Inthisalgorithm,edgesareaddedtothetreeone-by-one• Ifacycleresults,theedgeinthecyclewithmaximumweight
isremoved• TheuseofthismethodisshowninFigure8.15ca-clonpage
414
Data Structures and Algorithms in C++, Fourth Edition 46
Data Structures and Algorithms in C++, Fourth Edition 47
Connectivity• Inmanygraphproblemswewanttofindapathfromagiven
vertextoanyothervertex• Inundirectedgraphsthismeanstherearenoseparatepieces
inthegraph(subgraphs)• Inadigraph,wemaybeabletogettosomeverticesina
particulardirection,butnotreturntothestartingvertex
Data Structures and Algorithms in C++, Fourth Edition 48
Connectivity(continued)• ConnectivityinUndirectedGraphs
– Anundirectedgraphisconsideredtobeconnected ifthereisapathbetweenanytwoverticesofthegraph
– Wecanusethedepth-firstsearchalgorithmtodetermineconnectivityifthewhile loopheadingisremoved
– Whenthealgorithmcompletes,wechecktheedgeslisttoseeifitcontainsalltheverticesofthegraph
– Connectivityisdescribedintermsofdegrees;agraphismoreorlessconnecteddependingonthenumberofdifferentpathsbetweenvertices
– Ann-connected graphhasatleastn differentpathsbetweenanytwovertices
– Thismeanstherearen pathsbetweentheverticesthathavenoverticesincommon
Data Structures and Algorithms in C++, Fourth Edition 49
TopologicalSort• Atopologicalsort ofadirectedgraphisalinearorderingofits
verticessothat,foreveryedgeuv,u comesbeforev intheordering
• Forinstance,theverticesofthegraphmayrepresenttaskstobeperformed
• Theedgesmayrepresentconstraintsthatonetaskmustbeperformedbeforeanother
• Inthisapplication,atopologicalorderingisjustavalidsequenceforthetasks
• Atopologicalorderingispossibleifandonlyifthegraphhasnodirectedcycles,thatis,ifitisadirectedacyclicgraph(DAG)
Data Structures and Algorithms in C++, Fourth Edition 50
TopologicalSort(continued)• Thealgorithmforthetopologicalsortisasimpleone:topologicalSort(digraph)
for i = 1 to |V|
find a minimal vertex v;num(v) = i;
remove from digraph vertex v and all edges incident with v;
• Ascanbeseen,welocateavertex,v withnooutgoingedges• Suchavertexiscalledaminimalvertex orsink• Wethenremoveanyedgesleadingfromavertextov• Figure8.18showsthisprocess;thegraphinFigure8.18agoes
throughaseriesofdeletions(Figure8.18b-f)toproducethesequenceg, e, b, f, d, c, a
Data Structures and Algorithms in C++, Fourth Edition 51
TopologicalSort(continued)
Fig.8.18Executingatopologicalsort
Data Structures and Algorithms in C++, Fourth Edition 52
TopologicalSort(continued)• Itisnotactuallynecessarytodeletetheedgesandvertices
fromadigraphduringthisprocessing• Ifwecandeterminethatallsuccessorsofthevertexv have
beenprocessed,theycanbeconsidereddeleted• Thisisonceagainhandledbyapplyingthedepth-firstsearch
techniquesseenearlier• Basically,ifthesearchbacktrackstov,thenallitssuccessors
canbeassumedtohavealreadybeensearched• Thepseudocodeforthisalgorithmisshownonpages421and
423• Thetable(Figure8.18h)showshowthenumbersareassigned
foreachvertexofthegraphofFigure8.18a
Data Structures and Algorithms in C++, Fourth Edition 53
Networks• MaximumFlows
– Anetwork isadirectedgraphwhereeachedgehasacapacity andeachedgereceivesaflow
– Theamountofflowonanedgecannotexceedthecapacityoftheedge
– Aflowmustsatisfytherestrictionthattheamountofflowintoanodeequalstheamountofflowoutofit,exceptwhenitisasource,whichhasmoreoutgoingflow,orsink,whichhasmoreincomingflow
– Anetworkcanbeusedtomodeltrafficinaroadsystem,fluidsinpipes,currentsinanelectricalcircuit,oranythingsimilarinwhichsomethingtravelsthroughanetworkofnodes
– DelbertR.FulkersonandLesterR.Ford,Jr.developedthefirstcomputationalmodelsoftheseflowproblemsin1954
Data Structures and Algorithms in C++, Fourth Edition 54
Networks(continued)• MaximumFlows(continued)
– Thecentralproblemofthesenetworkmodelsistomaximizetheflowovertheedgesfromthesourcetothesink
– Thisisreferredtoasthemaximumflow (ormax-flow)problem– Figure8.19illustratesthisproblemforasmallwater-flownetworkof8
pipesand6pumpingstations;theedgesarelabeledwiththecapacityofthepipesinthousandsofgallons
Figure8.19Apipelinewitheightpipesandsixpumpingstations
Data Structures and Algorithms in C++, Fourth Edition 55
Networks(continued)• MaximumFlows(continued)
– AcentralaspectoftheFord-Fulkersonapproachistheconceptofacut– Acutseparatingsandt isasetofedgesbetweentwosets,X andX+– Everyvertexofthegraphisamemberofoneofthesetwosets;the
source,s,isinX andthesink,t,inX+– InFigure8.19,ifwechooseX ={s,a},thenX+ ={b,c,d,t},andthecutis
thesetofedges{{a,b},{s,c},{s,d}}– Thus,ifalltheseedgesarecut,thereisnowaytogetfroms tot– Nowwecandefinethecapacityofthecutasthesumofthecapacities
oftheedgesinthiscutset,so
cap{(a,b),(s,c),(s,d)}=cap(a,b)+cap(s,c)+cap(s,d)=19
Data Structures and Algorithms in C++, Fourth Edition 56
Networks(continued)• MaximumFlows(continue)
– Fromthis,wecaninferthemax-flowmin-cuttheorem:Theorem: Inanynetwork,themaximalflowfromstotisequaltotheminimalcapacityofanycut.
– Thismakesitfairlyclearthatwhiletheremaybecutswithlargercapacity,itisthecutwiththesmallestcapacitythatdeterminestheflowofthenetwork
– Forinstance,althoughthecapacityofourearliercutwas19,thetwoedgescomingtothesinkcan’ttransfermorethan9units
– Sowehavetosearchallthecutstofindtheonewiththesmallestcapacity,andtransferthroughthisasmanyunitsasthecapacityallows
– Toachievethis,we’llutilizeanewidea
Data Structures and Algorithms in C++, Fourth Edition 57
Matching
• Aparticularcompanyhasasetofjobs{a,b,c,d,e},andasetofapplicants{p,q,r,s,t}
• However,applicantp isonlyqualifiedforjobsa,b,andc;applicantq isonlyqualifiedforjobsb andd;similarrestrictionsexistfortheotherapplicants
• Ourproblemishowtomatchtheapplicantstothejobssuchthateachapplicanthasajobandalljobsareassigned
• Numerousproblemslikethisexist,andtheyareconvenientlymodeledusingbipartitegraphs
• Abipartitegraph isonewheretheverticescanbedividedintotwosets,suchthatanyedgehasonevertexineachset
Data Structures and Algorithms in C++, Fourth Edition 58
Matching(continued)
• Forthecompany,wecanconstructabipartitegraphwhereeachedgerelatesanapplicanttothejob(s)theyqualifyfor
• ThisisshowninFigure8.26
Fig.8.26Matchingfiveapplicantswithfivejobs
• Thetaskistomatcheachapplicantwithajob;thismaynotalwaysbepossible,sowewanttomatchasmanyaspossible
• ForagivengraphG =(V,E),amatchingM isdefinedasasubsetofedgesM⊆ E,wherenotwoedgesareadjacent
Data Structures and Algorithms in C++, Fourth Edition 59
Matching(continued)
• Amaximummatching isamatchingwherethenumberofunmatchedverticesisminimal
• ConsiderFigure8.27
Fig.8.27AgraphwithmatchingsM1={edge(cd),edge(ef)}andM2={edge(cd),edge(ge),edge(fh)}
• SetsM1 ={edge(cd),edge(ef)}andM2 ={edge(cd),edge(ge),edge(fh)}arematchings,butM2 isamaximummatching
• A perfectmatching isonewhereallverticesinthegrapharepaired
Data Structures and Algorithms in C++, Fourth Edition 60
GraphColoring
• Occasionally,wewanttodeterminetheminimumnumberofsetsofnon-coincidentvertices,wheresomeverticesineachsetareindependent
• Bythiswemeanthattheverticesarenotconnectedbyanyedge
• Byexample,wemayhaveseveraltaskstobeperformedbyseveralpeople
• Ifonetaskcanbeperformedbyonepersonatonetime,theschedulingmustbesuchthatthiscanbedone
• Wecanletthetaskrepresentverticesofagraph,andjoinwithanedgetwotasksthatrequirethesameperson
Data Structures and Algorithms in C++, Fourth Edition 61
GraphColoring(continued)
• Thenwetrytoconstructtheminimumnumberofsetsofindependenttasks
• Becauseallthetasksinagivensetcanbedoneconcurrently,thenumberofsetsindicatesthenumberoftimeslotsneeded
• Asavariationofthis,wecouldjoinwithanedgethosetasksthatcannotbeperformedconcurrently
• Asbefore,theindependentsetsindicatethetasksthatcanbeperformedatthesametime
• Howeverinthiscasetheminimumnumberofsetsindicatestheminimumnumberofpeopleneededtoperformthetasks
• Ingeneral,twoverticesarejoinedbyanedgeiftheycannotbemembersofthesameclass
Data Structures and Algorithms in C++, Fourth Edition 62
GraphColoring(continued)
• Wecanrestatetheproblemtosaythatverticesofagraphareassignedcolorssothatverticesjoinedbyanedgearedifferentcolors
• Sothetaskamountstocomingupwithagraphcoloring usingaminimumnumberofcolors
• Moreformally,givenasetofcolors,C,wedetermineafunctionf :V→C sothatifedge(vw)exists,f(v)≠f(w)andC isofminimumcardinality
• Thechromaticnumber ofagraphG istheminimumnumberofcolorsneededtocolorthegraph,denotedχ(G)
• Agraphwherek =χ(G)iscalledk-colorable
Data Structures and Algorithms in C++, Fourth Edition 63