Sie sind auf Seite 1von 10

DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm

ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 1

1) Howgraphsareusefulinthedesigningofgames?
Consider the following game. It is one of the many variants of Nim, also known as the
Marienbadgame.
Initiallythereisaheapofmatchesonthetablebetweentwoplayers.
The first player may remove as many matches as he likes, except that he must take at
leastoneandhemustleaveatleastone.
Theremustthereforebeatleasttwomatchesintheinitialheap.
Thereafter, each player in turn must remove at least one match and at most twice the
numberofmatcheshisopponentjusttook.
Theplayerwhoremovesthelastmatchwins.
Therearenodraws.
Suppose that at some stage in this game you find yourself in front of a pile of five
matches.
Youropponenthasjustpickeduptwomatches,andnowitisyourturntoplay.
You may take one, two, three or four matches: however you may not take all five, since
therulesforbidtakingmorethantwicewhatyouropponentjusttook.
Mostpeopleplayingthiskindofgamebegintorunthroughthepossibilitiesintheirheads:
"IfItakefourmatches,thatleavesjustoneformyopponent,whichhecantakeandwin;
ifItakethree,thatleavestwoformyopponent,andagainhecantakethemandwin;ifI
taketwo,thesamethinghappens;butifItakejustone,thenhewillhavefourmatchesin
frontofhimofwhichhecanonlytakeoneortwo.Inthiscasehedoesn'twinatonce,soit
iscertainlymybestmove."
Bylookingjustonemoveaheadinthissimplesituationtheplayercandeterminewhatto
donext.Inamorecomplicatedexample,hemayhaveseveralpossiblemoves.
To choose the best it may be necessary to consider not just the situation after his own
move, but to look further ahead to see how his opponent can counter each possible
move.
Andthenhemighthavetothinkabouthisownmoveaftereachpossiblecounter,andso
on.
To formalize this process of looking ahead, we represent the game by a directed graph.
Eachnodeinthegraphcorrespondstoapositioninthegame,andeachedgecorresponds
toamovefromonepositiontoanother.
Apositionin thegameisnotspecifiedmerelyby thenumberofmatchesthatremainon
thetable.Itisalsonecessarytoknowtheupperlimitonthenumberofmatchesthatmay
betakenonthenextmove.
Thenodesofthegraphcorrespondingtothisgamearethereforepairs(i,j).
Ingeneral,(i.j),1ji,indicatesthatimatchesremainonthetable,andthatanynumber
ofthembetween1andjmaybetakenonthenextmove.
Theedgesleavingthisposition,thatis,themovesthatcanbemade,gotothejnodes(i
k,min(2k,ik)),1<k<j.
Thenodecorrespondingtotheinitialpositioninagamewithnmatchesis(m,n1),n
2.
Theposition(0.0)losesthegame:ifaplayerisinthispositionwhenitishisturntomove,
hisopponenthasjusttakenthelastmatchandwon.
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 2

Figure shows part of the graph corresponding to this game. In fact, it is the part of the
graph needed by the player in the example above who faces a heap of five matches of
whichhemaytakefour:thisistheposition(5,4).
The heavy edges correspond to winning moves: in a winning position, choose one of the
heavyedgestowin.
There are no heavy edges leaving a losing position, corresponding to the fact that such
positions offer no winning move. We observe that the player who must move first in a
gamewithtwo,threeorfivematcheshasnowinningstrategy,whereashedoeshavesuch
astrategyinthegamewithfourmatches.
Todecidewhicharethewinningpositionsandwhichthelosingpositions,westartatthe
losingposition(0,0)andworkback.
Thisnodehasnosuccessor,andaplayerwhofindshimselfinthispositionlosesthegame.
Inanyofthenodes(1,1),(2,2)or(3,3),aplayercanmakeamovethatputshisopponent
inthelosingposition.Thesethreenodesarethereforewinningnodes.
From(2,1)theonlypossiblemoveisto(1,1).
Inposition(2,1)aplayeristhereforeboundtoputhisopponentinawinningposition,so
(2,1)itselfisalosingposition.
Asimilarargumentappliestothelosingposition(3,2).
2) Explainthetraversaltechniquesfortreetraversal.

Thefollowingarethetechniquesfortraversingthetrees:
1) Preorder
Totraversethetreeinpreorder,performthefollowingsteps:
i) Visittheroot.
ii) Traversetheleftsubtreeinpreorder.
iii) Traversetherightsubtreeinpreorder.
2) Inorder
i) Traversetheleftsubtreeininorder.
ii) Visittheroot.
iii) Traversetherightsubtreeininorder.
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page S

3) Postorder
i) TraversetheleftsubtreeinPostorder.
ii) TraversetherightsubtreeinPostorder.
iii) Visittheroot.
3) Explainpreconditioning.
Ifwehavetosolveseveralsimilarinstancesofthesameproblem,itmaybeworthwhileto
invest some time in calculating auxiliary results that can thereafter be used to speed up
thesolutionofeachinstance.Thisispreconditioning.
Informally, let a be the time it takes to solve a typical instance when no auxiliary
informationisavailable.
Let b be the time it takes to solve a typical instance when auxiliary information is
available.
Letpbethetimeneededtocalculatethisextrainformation.
To solve n typical instances takes time na without preconditioning and time p + nb if
preconditioningisused.
Providedb<a,itisadvantageoustousepreconditioningwhenn>p/(ab).
4) Explainprenumandpostnumwithexample.
Prenum
prenum[v]isthenumberassignedtothenodevwhenwetraversethetreeinpreorder.

Postnum
postnum[v]isthenumberassignedtothenodevwhenwetraversethetreeinpostorder.

Inthefigurebelow,thenumbersappeartotheleftandtherightofthenodearetheprenum
andpostnumofthenoderespectively.


DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 4

5) ExplainDepthFirstSearchofgraphwithexample.
LetG=(N,A)beanundirectedgraphallofwhosenodeswewishtovisit.
Supposeitissomehowpossibletomarkanodetoshowithasalreadybeenvisited.
Tocarryoutadepthfirsttraversalofthegraph,chooseanynodevNasthestarting
point.
Markthisnodetoshowithasbeenvisited.
Next,ifthereisanodeadjacenttovthathasnotyetbeenvisited,choosethisnodeasa
newstartingpointandcallthedepthfirstsearchprocedurerecursively.
Onreturnfromtherecursivecall,ifthereisanothernodeadjacenttovthathasnotbeen
visited,choosethisnodeasthenextstartingpoint,calltheprocedurerecursivelyonce
again,andsoon.
Whenallthenodesadjacenttovaremarked,thesearchstartingatvisfinished.
IfthereremainanynodesofGthathavenotbeenvisited,chooseanyoneofthemasa
newstartingpoint,andcalltheprocedureyetagain.
ContinuethusuntilallthenodesofGaremarked.
Hereistherecursivealgorithm.

proceduredfsearch(G)
foreachvNdomark[v]notvisited
foreachvNdo
ifmark[v]visitedthendfs(v)

proceduredfs(v)
{Nodevhasnotpreviouslybeenvisited}
mark[v]visited
foreachnodewadjacenttovdo
ifmark[w]visitedthendfs(w)

Example:
Considerthefollowinggraph.

Thedepthfirstsearchfortheabovegraphcanbeperformedasfollows:
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page S

6) ExplainArticulationpoint.Alsoexplainhowtofindarticulationpointsfromthegraph.
Anodevofaconnectedgraphisanarticulationpointifthesubgraphobtainedbydeletingv
andtheentireedgesincidentonvisnolongerconnected.

For example, node 1 is an articulation point of the graph in the above figure; If we delete it,
thereremaintwoconnectedcomponents{2,3,5,6}and{4,7,8}.

The following is the complete algorithm for finding the articulation points of an undirected
graphG:

1) Carry out a depthfirst search in G, starting from any node. Let T be the tree
generated by this search, and for each node v of G, let prenum[v] be the number
assignedbythesearch.
2) TraverseTinpostorder.Foreachnodevvisited,calculatehighest[v]astheminimum
of
(a) prenumlv];
(b) prenum [w] for each node w such that there is an edge {v, w} in G with no
correspondingedgeinT;and
(c) highest[x]foreverychildxofv.
3) DeterminethearticulationpaintsofGasfollows.
(a) TherootofTisanarticulationpointifandonlyifithasmorethanonechild.
(b) Anyothernodevisanarticulationpointifandonlyifithasachildxsuchthat
highest[x]>prenum[v].

7) DepthFirstSearchforDirectedgraph
The algorithm is essentially the same as for undirected graphs, the difference residing in
theinterpretationoftheword"adjacent".
Inadirectedgraph,nodewisadjacenttonodevifthedirectededge(v,w)exists.If (v, w)
existsbut(w,v)doesnot,thenwisadjacenttovbutvisnotadjacenttow.

DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 6

8) AcyclicGraphs:Topologicalsorting
Directedacyclicgraphscanbeusedtorepresentanumberofinterestingrelations.
Thisclassincludestrees,butislessgeneralthantheclassofalldirectedgraphs.
Figurebelowillustratespartialorderingdefinedonthepositiveintegers:herethereisan
edgefromnodeItonodejifandonlyifIisaproperdivisorofj.

Depthfirstsearchcanbeusedtodetectwhetheragivendirectedgraphisacyclic.
Itcanalsobeusedtodetermineatopologicalorderingofthenodesofadirectedacyclic
graph.
Inthiskindoforderingthenodesofthegrapharelistedinsuchawaythatifthereexists
anedge(i,j),thennodeiprecedesnodejinthelist.
Forexample,forthegraphgivenabove,thenaturalorder1,2,3,4,5,6,8,12,14isadequate,
whereas1,3,6,2,4,12,8,24willnotdo,becausethegraphincludesanedge(2,6)andso2
mustprecede6inthelist.
Topologicalsortingcanbeobtainedbyapplyingdepthfirstsearchtechniqueonthegraph
andthenreversetheorderoftheresultinglistofnodes.

9) ExplainBreadthfirstsearchtechnique.
Given a graph G = (V, E) and a distinguished source vertex s, breadthfirst search
systematicallyexplorestheedgesofGto"discover"everyvertexthatisreachablefroms.
Itcomputesthedistance(smallestnumberofedges)fromstoeachreachablevertex.
Italsoproducesa"breadthfirsttree"withrootsthatcontainsallreachablevertices.
For any vertex v reachable from s, the path in the breadthfirst tree from s to v
corresponds to a "shortest path" from s to v in G, that is, a path containing the smallest
numberofedges.
Thealgorithmworksonbothdirectedandundirectedgraphs.
Breadthfirstsearchissonamedbecauseitexpandsthefrontierbetweendiscoveredand
undiscoveredverticesuniformlyacrossthebreadthofthefrontier.
That is, the algorithm discovers all vertices at distance k from s before discovering any
verticesatdistancek+1.
Thealgorithmforbreadthfirstsearchisasfollows:

proceduresearch(G)
foreachvNdomark[v]notvisited
foreachvNdo
ifmark[v]visitedthenbfs(v)

procedurebfs(v)
Qemptyqueue
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 7

mark[v]visited
enqueuevintoQ
whileQisnotemptydo
ufirst(Q)
dequeueufromQ
foreachnodewadjacenttoudo
ifmark[w]visitedthenmark[w]visited
enqueuewintoQ

10) Howbacktrackingisappliedfortheproblemof01knapsack?
Wearegivenacertainnumberofobjectsandaknapsack.
Weshallsupposethatwehaventypesofobject,andthatanadequatenumberofobjects
ofeachtypeareavailable.
Thisdoesnotaltertheprobleminanyimportantway.Fori=1,2,...,n,anobjectoftypei
hasapositiveweightw
i
andapositivevaluev
i
.
TheknapsackcancarryaweightnotexceedingW.
Ouraim istofilltheknapsackinawaythat maximizesthevalueoftheincludedobjects,
whilerespectingthecapacityconstraint.
Wemaytakeanobjectortoleaveitbehind,butwemaynottakeafractionofanobject.
Supposeforconcretenessthatwewishtosolveaninstanceoftheprobleminvolvingfour
typesofobjects,whoseweightsarerespectively2,3,4and5units,andwhosevaluesare
3,5,6and10.Theknapsackcancarryamaximumof8unitsofweight.
Thiscanbedoneusingbacktrackingbyexploringtheimplicittreeshownbelow.

Hereanodesuchas(2,3;8)correspondstoapartialsolutionofourproblem.
Thefigurestotheleftofthesemicolonaretheweightsoftheobjectswehavedecidedto
include,andthefiguretotherightisthecurrentvalueoftheload.
Moving down from a node to one of its children corresponds to deciding which kind of
object to put into the knapsack next. Without loss of generality we may agree to load
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 8

objectsintotheknapsackinorderofincreasingweight.
Initiallythepartialsolutionisempty.
Thebacktrackingalgorithmexploresthetreeasinadepthfirstsearch,constructingnodes
andpartialsolutionsasitgoes.
Inthe example,thefirstnodevisitedis(2;3),thenextis(2,2;6),thethirdis(2,2,2;9)and
thefourth(2,2,2.2;12).
Aseachnewnodeisvisited,thepartialsolutionisextended.
Aftervisitingthesefournodes,thedepthfirstsearchisblocked:node(2,2,2,2;12)hasno
unvisitedsuccessors(indeednosuccessorsatall),sinceaddingmoreitemstothispartial
solutionwouldviolatethecapacityconstraint.
Since this partial solution may turn out to be the optimal solution to our instance, we
memorizeit.
Thedepthfirstsearchnowbacksuptolookforothersolutions.
At each step back up the tree, the corresponding item is removed from the partial
solution.
In the example, the search first backs up to (2,2,2;9), which also has no unvisited
successors;onestepfurtherupthetree,however,atnode(2,2;6),twosuccessorsremain
tobevisited.
After exploring nodes (2,2,3; 11) and (2,2,4; 12), neither of which improves on the
solutionpreviouslymemorized,thesearchbacksuponestagefurther,andsoon.
Exploringthetreeinthisway,(2,3,3;13)isfoundtobeabettersolutionthantheonewe
have,andlater(3,5;15)isfoundtobebetterstill.
Since no other improvement is made before the search ends, this is the optimal solution
totheinstance.
Algorithmcanbegivenasfollows:

functionbackpack(i.r)
{Calculatesthevalueofthebestloadthatcanbeconstructedusingitemsoftypesiton
andwhosetotalweightdoesnotexceedr}
b0
{Tryeachallowedkindofiteminturn}
forkitondo
ifw[k]rthen
bmax(b,v[k]+backpack(k,rw[k]))
returnb

Nowtofindthevalueofthebestload,callbackpack(1,W).
11) Explain8queensproblem.
The classic problem of placing eight queens on a chessboard in such a way that none of
themthreatensanyoftheothers.
Recallthataqueenthreatensthesquaresinthesamerow,inthesamecolumn,oronthe
samediagonals.
Themostobviouswaytosolvethisproblemconsistsoftryingsystematicallyalltheways
ofplacingeightqueensonachessboard,checkingeachtimetoseewhetherasolutionhas
beenobtained.
Thisapproachisofnopracticaluse,evenwithacomputer,sincethenumberofpositions
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 9

wewouldhavetocheckis(
64
8
)4426165368.
Thefirstimprovementwemighttryconsistsofneverputtingmorethanonequeenonany
givenrow.
This reduces the computer representation of the chessboard to a vector of eight
elements,eachgivingthepositionofthequeeninthecorrespondingrow.
Forinstance,thevector(3,1,6,2,8,6,4,7)representsthepositionwherethequeenonrow
1isincolumn3,thequeenonrow2isincolumn1,andsoon.
Backtracking allows us to do better than this. As a first step, we reformulate the eight
queens problem as a tree searching problem. We say that a vector V[1k] of integers
between1and8iskpromising,for0k8,ifnoneofthekqueensplacedinpositions
(1,V[1]),(2,V[2]),,(k,V[k])threatensanyoftheothers.
Mathematically, a vector V is kpromising if, for every pair of integers i and j between 1
andkwithij,wehaveV[i]V[j]doesnotbelongsto{ij,0,ji}.Fork1,anyvectorVis
kpromising.
Solutionstotheeightqueensproblemcorrespondtovectorsthatare8promisng.
LetNbethesetofkpromisingvectors,0k8.
Let G = (N, A) be the directed graph such that (U, v) e A if and only if there exists an
integerk,0k8suchthat,
Uiskpromising,
Vis(k+1)promising,and
U[i]=V[i]foreveryie[1..k].

Thealgorithmforthe8queensproblemisgivenasfollows:

procedurequeens(k,col,diag45,diag135)
{sol[1..k]iskpromising,
col={sol[i]|1ik},
diag45={sol[i]i+1|1ik},and
diag135={sol[i]+i1|1ik}}
ifk=8then{an8promisingvectorisasolution}
writesol
else{explore(k+1promisingvectorisasolution}
forj1to8do
ifjdoesnotbelongstocolandjkdoesnotbelongstodiag45andj+
kdoesnotbelongstodiag135
thensol[k+1]j
{sol[1..k+1]is(k+1)promising}
queens(k+1,colU{j},
diag45U{jk},diag135U{j+k})

12) Explainminmaxprinciple.
Whichever search technique we use, the awkward fact remains that for a game such as
chessacompletesearchoftheassociatedgraphisoutofthequestion.
Inthissituationwehavetobecontentwithapartialsearcharoundthecurrentposition.
Thisistheprincipleunderlyinganimportantheuristiccalledminimax.
Although this heuristic does not allow us to be certain of winning whenever this is
possible, it finds a move that may reasonably be expected to be among the best moves
DarshanInstitueofEngineering&Technology 150703DesignandAnalysisofAlgorithm
ComputerEngineering Chapter6ExploringGraphs
Baiuik A. Boshi Page 1u

available,whileexploringonlypartofthegraphstartingfromsomegivenposition.
Exploration of the graph is normally stopped before the terminal positions are reached,
using one of several possible criteria, and the positions where exploration stopped are
evaluatedheuristically.
Inasense,thisismerelyasystematicversionofthemethodusedbysomehumanplayers
thatconsistsoflookingaheadasmallnumberofmoves.

Das könnte Ihnen auch gefallen