Tải bản đầy đủ - 0 (trang)
2 Floyd's Algorithm for Shortest Paths

2 Floyd's Algorithm for Shortest Paths

Tải bản đầy đủ - 0trang



Figure3.2:Aweighted,directedgraph.

Aproblemthathasmanyapplicationsisfindingtheshortestpathsfrom

eachvertextoallothervertices.Clearly,ashortestpathmustbeasimple

path.InFigure3.2therearethreesimplepathsfromv1tov3—namely

[v1,v2,v3][v1,v4,v3]and[v1,v2,v4,v3].Because



[v1,v4,v3]istheshortestpathfromv1tov3.Asmentionedpreviously,

onecommonapplicationofshortestpathsisdeterminingtheshortest

routesbetweencities.

TheShortestPathsproblemisanoptimizationproblem.Therecanbe

morethanonecandidatesolutiontoaninstanceofanoptimization

problem.Eachcandidatesolutionhasavalueassociatedwithit,anda

solutiontotheinstanceisnaycandidatesolutionthathasanoptimal

value.Dependingontheproblem,theoptimalvalueiseitherthe

minimumorthemaximum.InthecaseoftheShortestPathsproblem,a

candidatesolutionisapathfromonevertextoanother,thevalueisthe

lengthofthepath,andtheoptimalvalueistheminimumoftheselengths.

Becausetherecanbemorethanoneshortestpathfromonevertexto

another,ourproblemstofindanyoneoftheshortestpaths.Anobvious

algorithmforthisproblemwouldbetodetermine,foreachvertex,the

lengthsofallthepathsfromthatvertextoeachothervertex,andto

computetheminimumoftheselengths.However,thisalgorithmisworse



thanexponential-time.Forexample,supposethereisanedgefromevery

vertextoeveryothervertex.Thenasubsetofallthepathsfromone

vertextoanothervertexisthesetoftheallthosepathsthatstartatthe

firstvertex,endattheothervertex,andpassthroughalltheother

vertices.Becausethesecondvertexonsuchapathcanbeanyofn−2

vertices,thethirdvertexonsuchapathcanbeanyofn−3vertices,…,

andthesecond-to-lastvertexonsuchapathcanbeonlyonevertex,the

totalnumberofpathsfromonevertextoanothervertexthatpassthrough

alltheotherverticesis



whichisworsethanexponential.Weencounterthissamesituationin

manyoptimizationproblems.Thatis,theobviousalgorithmthat

considersallpossibilitiesisexponential-timeorworse.Ourgoalistofind

amoreefficientalgorithm.

Usingdynamicprogramming,wecreateacubic-timealgorithmforthe

ShortestPathsproblem.Firstwedevelopanalgorithmthatdetermines

onlythelengthsoftheshortestpaths.Afterthatwemodifyittoproduce

shortestpathsaswell.Werepresentaweightedgraphcontainingn

verticesbyanarrayWwhere



Becausevertexvjissaidtobeadjacenttoviifthereisanedgefromvi

tovj,thisarrayiscalledtheadjacencymatrixrepresentationofthe

graph.ThegraphinFigure3.2isrepresentedinthismannerinFigure

3.3.ThearrayDinFigure3.3containsthelengthsoftheshortestpaths

inthegraph.Forexample,D[3][5]is7because7isthelengthofa

shortestpathfromv3tov5.Ifwecandevelopawaytocalculatethe

valuesinDfromthoseinW,wewillhaveanalgorithmfortheShortest

Pathproblem.Weaccomplishthisbycreatingasequenceofn+1arrays

D(k),where0≤k≤nandwhere





Figure3.3:WrepresentsthegraphinFigure3.2andDcontainsthe

lengthsoftheshortestpaths.OuralgorithmfortheShortestPaths

problemcomputesthevaluesinDfromthoseinW.

BeforeshowingwhythisenablesustocomputeDfromW,let'sillustrate

themeaningoftheitemsinthesearrays.

Example3.2

WewillcalculatesomeexemplaryvaluesofDk[i][j]forthegraphin

Figure3.2



Thelastvaluecomputed,D(5)[2][5],isthelengthofashortestpathfrom

v2tov5thatisallowedtopassthroughanyoftheothervertices.This

meansthatitisthelengthofashortestpath.



BecauseD(n)[i[j]isthelengthofashortestpathfromvitovjthatis

allowedtopassthroughanyoftheothervertices,itisthelengthofa

shortestpathfromvitovj.BecauseD(0)[i][j]isthelengthofashortest

paththatisnotallowedtopassthroughanyothervertices,itistheweight

ontheedgefromv1tovj.Wehaveestablishedthat



Therefore,todetermineDfromWweneedonlyfindawaytoobtainD(n)

fromD(0).Thestepsforusingdynamicprogrammingtoaccomplishthis

areasfollows:

1. Establisharecursiveproperty(process)withwhichwecan

computeD(k)fromD(k−1).

2. Solveaninstanceoftheprobleminabottom-upfashionby

repeatingtheprocess(establishedinStep1)fork=1ton.This

createsthesequence



WeaccomplishStep1byconsideringtwocases:

Case1.Atleastoneshortestpathfromvitovj,usingonlyverticesin{v1,

v2…,vk}asintermediatevertices,doesnotusevk.Then



AnexampleofthiscaseinFigure3.2isthat



becausewhenweincludevertexv5,theshortestpathfromv1tov3is

still[v1,v4,v3].



Case2.Allshortestpathsfromv1tovj,usingonlyverticesin{v1,v2,…,

vk}asintermediatevertices,dousevk.Inthiscaseanyshortestpath

appearsasinFigure3.4.Becausevkcannotbeanintermediatevertex

onthesubpathfromvitovk,thatsubpathusesonlyverticesin{v1,v2....,

vk−1}asintermediates.Thisimpliesthatthesubpath'slengthmustbe

equaltoDk−1[i][k]forthefollowingreasons:First,thesubpath'slength

cannotbeshorterbecauseDk−1)[i][k]isthelengthofashortestpath

fromv1itvkusingonlyverticesin{v1,v2,…,vk−1}asintermediates.

Second,thesubpath'slengthcannotbelongerbecauseifitwere,we

couldreplaceitinFigure3.4byashortestpath,whichcontradictsthat

factthattheentirepathinFigure3.4isashortestpath.Similarly,the

lengthofthesubpathfromvktovjinFigure3.4mustbeequaltoDk-1)

[k][j].Therefore,inthesecondcase





Figure3.4:Theshortestpathusesvk



AnexampleofthesecondcaseinFigure3.2isthat



BecausewemusthaveeitherCase1orCase2,thevalueofD(k[i][j]is

theminimumofthevaluesontherightinEqualities3.3and3.4.This

meansthatwecandetermineD(k)fromD(k−1)asfollows:



WehaveaccomplishedStep1inthedevelopmentofadynamic

programmingalgorithm.ToaccomplishStep2,weusetherecursive

propertyinStep1tocreatethesequenceofarraysshowninExpression

3.2.Let'sdoanexampleshowinghoweachofthesearraysiscomputed

fromthevariousone.

Example3.3

GiventhegraphinFigure3.2,whichisrepresentedbytheadjacency

matrixWinFigure3.3,somesamplecomputationsareasfollows(recall

thatD(0)=W):



OncethewholearrayD(1)iscomputed,thearrayD(2)iscomputed.A

samplecomputationis



AftercomputingallofD(2),wecontinueinsequenceuntilD(5)is

computed.ThisfinalarrayisD,thelengthsoftheshortestpaths.It

appearsontehrightinFigure3.3.



NextwepresentthealgorithmdevelopedbyFloyd(1962)andknownas

Floyd'salgorithm.Followingthealgorithm,weexplainwhyitusesonly

onearrayDbesidestheinputarrayW.



Algorithm3.3:Floyd'sAlgorithmforShortestPaths

Problem:Computetheshortestpathsfromeachvertexinaweighted

graphtoeachoftheothervertices.Theweightsarenonnegative

numbers.

Inputs:Aweighted,directedgraphandn,thenumberofverticesinthe

graph.Thegraphisrepresentedbyatwo-dimensionalarrayWwhichhas

bothitsrowsandcolumnsindexedfrom1ton,whereW[i][j]istheweight

ontheedgefromtheithvertextothejthvertex.

Outputs:Atwo-dimensionalarrayD,whichhasbothitsrowsand

columnsindexedfrom1ton,whereD[i][j]isthelengthofashortestpath

fromtheithvertextothejthvertex.

voidfloyd(intn

constnumberW[][]

numberD[][]

{

indexi,j,k;

D=W;

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(i=1;j<=n;j++)

D[i][j]=minimum(D[i][j],D[i][k]+D[k][j]);

}



WecanperformourcalculationsusingonlyonearrayDbecausethe

valuesinthekthrowandthekthcolumnarenotchangedduringthekth

iterationoftheloop.Thatis,inthekthiterationthealgorithmassigns.



whichclearlyequalsD[i][k],and



whichclearlyequalsD[k][j].Duringthekthiteration,D[i][j]iscomputed



fromonlyitsownvalueandvaluesinthekthrowandthekthcolumn.

Becausethesevalueshavemaintainedtheirvaluesfromthe(k−1)st

iteration,theyarethevalueswewant.Asmentionedbefore,sometimes

afterdevelopingadynamicprogrammingalgorithm,itispossibleto

revisethealgorithmtomakeitmoreefficientintermsofspace.

NextweanalyzeFloyd'sAlgorithm.

AnalysisofAlgorithm3.3Every-CaseTimeComplexity(Floyd's

AlgorithmforShortestPaths)

Basicoperation:Theinstructioninthefor-jloop.

Inputsize:n,thenumberofverticesinthegraph.

Wehavealoopwithinaloopwithinaloop,withnpassesthrougheach

loop.So.



ThefollowingmodificationtoAlgorithmproducesshortestpaths.

Algorithm3.4:Floyd'sAlgorithmforShortestPaths2

Problem:sameasinAlgorithm3.3,exceptshortestpathsarealso

created.

Additionaloutputs:anarrayP,whichhasbothitsrowsandcolumns

indexedfrom1ton,where



voidfloyd2(intn,



constnumberW[][],

numberD[][],

indexP[][])

{

index,i,j,k;

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

P[i][j=0;

D=W

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if(D[i][k]+D[k][j]
P[i][j]=k;

D[i][j[=D[i[[k]+D[k][j];

}

}



Figure3.5showsthearrayPthatiscreatedwhenthealgorithmis

appliedtothegraphinFigure3.2.





Figure3.5:ThearrayPproducedwhenAlgorithm3.4isappliedtothe

graphinFigure3.2.



Thefollowingalgorithmproducesashortestpathfromvertexvqtove

usingthearrayP.

Algorithm3.5:PrintShortestPath

Problem:Printtheintermediateverticesonashortestpathfromone

vertextoanothervertexinaweightedgraph.

Inputs:thearrayPproducedbyAlgorithm3.4,andtwoindices,qandr,

ofverticesinthegraphthatistheinputtoAlgorithm3.4.



Outputs:theintermediateverticesonashortestpathfromvqtovr.

voidpath(indexq,r)

{

if(P[q][r]!=0){

path(q,P[q][r]);

cout<<"v"<
path(P[q][r],r);

}

}



RecalltheconventionestablishedinChapter2ofmakingonlyvariables.

whosevaluescanchangeintherecursivecalls,inputstorecursive

routines.Therefore,thearrayPisnotaninputtopath.Ifthealgorithm

wereimplementedbydefiningpglobally,andwewantedashortestpath

fromvqtovr,thetop-levelcalltopathwouldbeasfollows:

path(q,r);

GiventhevalueofPinFigure3.5,ifthevaluesofqandrwere5and3,

respectively,theoutputwouldbe



Thesearetheintermediateverticesonashortestpathfromv5tov3.

IntheexercisesweestablishthatW(n∊)Θ(n)forAlgorithm3.5



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

2 Floyd's Algorithm for Shortest Paths

Tải bản đầy đủ ngay(0 tr)

×