chapter 8: graphs - sign in - google...
TRANSCRIPT
![Page 1: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/1.jpg)
Chapter8:Graphs
![Page 2: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/2.jpg)
IntroductoryRemarks
• Althoughtreesarequiteflexible,theyhaveaninherentlimitationinthattheycanonlyexpresshierarchicalstructures
• Fortunately,wecangeneralizeatreetoformagraph,inwhichthislimitationisremoved
• Informally,agraphisacollectionofnodesandtheconnectionsbetweenthem
• Figure8.1illustratessomeexamplesofgraphs;noticethereistypicallynolimitationonthenumberofverticesoredges
• Consequently,graphsareextremelyversatileandapplicabletoawidevarietyofsituations
• Graphtheoryhasdevelopedintoasophisticatedfieldofstudysinceitsoriginsintheearly1700s
Data Structures and Algorithms in C++, Fourth Edition 2
![Page 3: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/3.jpg)
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
![Page 4: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/4.jpg)
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
![Page 5: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/5.jpg)
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
![Page 6: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/6.jpg)
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
![Page 7: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/7.jpg)
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
![Page 8: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/8.jpg)
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
ìï= íïî
![Page 9: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/9.jpg)
9Data Structures and Algorithms in C++, Fourth Edition
![Page 10: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/10.jpg)
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
ì= íî
![Page 11: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/11.jpg)
GraphRepresentation(continued)• AnexampleofanincidencematrixisshowninFigure8.2e• Foramultigraph,manycolumnsarethesame,andacolumn
withasingle1representsaloop• Asfarasusage,theproperstructuredependstoagreat
extentonthekindsofoperationsthatneedtobedone
11Data Structures and Algorithms in C++, Fourth Edition
![Page 12: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/12.jpg)
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
![Page 13: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/13.jpg)
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
![Page 14: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/14.jpg)
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
![Page 15: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/15.jpg)
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
![Page 16: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/16.jpg)
GraphTraversals(continued)
Fig.8.4ThedepthFirstSearch()algorithmappliedtoadigraph
• Noticeinthiscaseweendupwithaforestofthreetrees,becausethetraversalmustfollowthedirectionoftheedges
• Thereareanumberofalgorithmsbasedondepth-firstsearching
• However,somearemoreefficientiftheunderlyingmechanismisbreadth-firstinstead
Data Structures and Algorithms in C++, Fourth Edition 16
![Page 17: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/17.jpg)
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
![Page 18: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/18.jpg)
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
![Page 19: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/19.jpg)
GraphTraversals(continued)
Fig.8.5AnexampleofapplicationofthebreadthFirstSearch()algorithmtoagraph
Fig.8.6ThebreadthFirstSearch()algorithmappliedtoadigraph
Data Structures and Algorithms in C++, Fourth Edition 19
![Page 20: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/20.jpg)
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
![Page 21: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/21.jpg)
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
![Page 22: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/22.jpg)
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
![Page 23: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/23.jpg)
23Data Structures and Algorithms in C++, Fourth Edition
![Page 24: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/24.jpg)
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
![Page 25: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/25.jpg)
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
![Page 26: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/26.jpg)
ShortestPaths(continued)• Noticethattheset’sstructureisnotindicated;recallitisthe
structurethatdeterminesefficiency• Figure8.7illustratesthisforthegraphinpart(a)
Fig.8.7AnexecutionofDijkstraAlgorithm()
Data Structures and Algorithms in C++, Fourth Edition 26
![Page 27: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/27.jpg)
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
![Page 28: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/28.jpg)
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
![Page 29: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/29.jpg)
ShortestPaths(continued)
Data Structures and Algorithms in C++, Fourth Edition 29
Fig.8.8FordAlgorithm()appliedtoadigraphwithnegativeweights
• InthecaseofDijkstra’salgorithm,weobservedthattheefficiencycanbeimprovedbythechoiceofdatastructure
• Thisinturnimpactsthewaytheedgesandverticesarescanned
![Page 30: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/30.jpg)
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
![Page 31: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/31.jpg)
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
![Page 32: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/32.jpg)
ShortestPaths(continued)• Figure8.9illustratesthisproblemforthegraphofFigure8.8a
Fig.8.9AnexecutionoflabelCorrectingAlgorithm(),whichusesaqueue
• Ascanbeseen,anumberofverticesareupdatedmultipletimes
Data Structures and Algorithms in C++, Fourth Edition 32
![Page 33: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/33.jpg)
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
![Page 34: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/34.jpg)
ShortestPaths(continued)
Fig.8.10AnexecutionoflabelCorrectingAlgorithm(),whichappliesadeque
• Theuseofadequedoessufferfromoneproblem,however• Itsworstcaseperformanceisexponentialinthenumberof
vertices
Data Structures and Algorithms in C++, Fourth Edition 34
![Page 35: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/35.jpg)
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
![Page 36: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/36.jpg)
ShortestPaths(continued)• Avertexwillbeaddedtotheendofthefirstlistifthevalueof
itslabelisbelowthethresholdlevel• Otherwiseitwillbeaddedtothesecondlist• Ifthefirstlistbecomesempty,thethresholdismodifiedtoa
valuegreaterthantheminimumlabelvalueofallverticesinthesecondlist
• Thenthoseverticeswhoselabelsarelessthanthenewthresholdaremovedfromthesecondlisttothefirstlist
• Yetanotherapproachisthesmalllabelfirstmethod• Inthismethod,avertexisplacedatthefrontofthedequeif
itslabelissmallerthanthelabelofthecurrentfrontofthedeque;otherwiseitisplacedattherear
Data Structures and Algorithms in C++, Fourth Edition 36
![Page 37: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/37.jpg)
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
![Page 38: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/38.jpg)
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
![Page 39: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/39.jpg)
CycleDetection
• Numerousalgorithmsrelyontheirabilitytodetectcyclesingraphs
• OurconsiderationoftheWarshall-Floydalgorithminthepreviousexampledemonstratedthatitcandetectcycles
• However,itscubicordermakesittooinefficienttouseinallcircumstances,soothermethodshavetobeconsidered
• Onealgorithm,basedonthedepthFirstSearch()routine,workswellforundirectedgraphs
• Thepseudocodeforthisisshownonpage408
Data Structures and Algorithms in C++, Fourth Edition 39
![Page 40: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/40.jpg)
CycleDetection
Data Structures and Algorithms in C++, Fourth Edition 40
![Page 41: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/41.jpg)
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
![Page 42: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/42.jpg)
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
![Page 43: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/43.jpg)
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
![Page 44: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/44.jpg)
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
![Page 45: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/45.jpg)
SpanningTrees(continued)
Data Structures and Algorithms in C++, Fourth Edition 45
![Page 46: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/46.jpg)
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
![Page 47: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/47.jpg)
Data Structures and Algorithms in C++, Fourth Edition 47
![Page 48: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/48.jpg)
Connectivity• Inmanygraphproblemswewanttofindapathfromagiven
vertextoanyothervertex• Inundirectedgraphsthismeanstherearenoseparatepieces
inthegraph(subgraphs)• Inadigraph,wemaybeabletogettosomeverticesina
particulardirection,butnotreturntothestartingvertex
Data Structures and Algorithms in C++, Fourth Edition 48
![Page 49: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/49.jpg)
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
![Page 50: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/50.jpg)
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
![Page 51: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/51.jpg)
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
![Page 52: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/52.jpg)
TopologicalSort(continued)
Fig.8.18Executingatopologicalsort
Data Structures and Algorithms in C++, Fourth Edition 52
![Page 53: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/53.jpg)
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
![Page 54: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/54.jpg)
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
![Page 55: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/55.jpg)
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
![Page 56: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/56.jpg)
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
![Page 57: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/57.jpg)
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
![Page 58: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/58.jpg)
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
![Page 59: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/59.jpg)
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
![Page 60: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/60.jpg)
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
![Page 61: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/61.jpg)
GraphColoring
• Occasionally,wewanttodeterminetheminimumnumberofsetsofnon-coincidentvertices,wheresomeverticesineachsetareindependent
• Bythiswemeanthattheverticesarenotconnectedbyanyedge
• Byexample,wemayhaveseveraltaskstobeperformedbyseveralpeople
• Ifonetaskcanbeperformedbyonepersonatonetime,theschedulingmustbesuchthatthiscanbedone
• Wecanletthetaskrepresentverticesofagraph,andjoinwithanedgetwotasksthatrequirethesameperson
Data Structures and Algorithms in C++, Fourth Edition 61
![Page 62: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/62.jpg)
GraphColoring(continued)
• Thenwetrytoconstructtheminimumnumberofsetsofindependenttasks
• Becauseallthetasksinagivensetcanbedoneconcurrently,thenumberofsetsindicatesthenumberoftimeslotsneeded
• Asavariationofthis,wecouldjoinwithanedgethosetasksthatcannotbeperformedconcurrently
• Asbefore,theindependentsetsindicatethetasksthatcanbeperformedatthesametime
• Howeverinthiscasetheminimumnumberofsetsindicatestheminimumnumberofpeopleneededtoperformthetasks
• Ingeneral,twoverticesarejoinedbyanedgeiftheycannotbemembersofthesameclass
Data Structures and Algorithms in C++, Fourth Edition 62
![Page 63: Chapter 8: Graphs - Sign in - Google Accountsportal.cs.ku.edu.kw/~almutawa/cs201/cs201_Graphs.pdf · · 2016-11-27Chapter 8: Graphs. Introductory Remarks ... Fourth Edition 13](https://reader030.vdocuments.net/reader030/viewer/2022020303/5b053e767f8b9a0a548e9dc2/html5/thumbnails/63.jpg)
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