63
Chapter 8: Graphs

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

  • Upload
    lydieu

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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