28
This document is copyright (C) Stanford Computer Science, Marty Stepp, Victoria Kirst, licensed under Creative Commons Attribution 2.5 License. All rights reserved. CS 106B, Lecture 11 Exhaustive Search and Backtracking This document is copyright (C) Stanford Computer Science and Ashley Taylor, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Marty Stepp, Chris Gregg, Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others

CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

  • Upload
    others

  • View
    27

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

Thisdocumentiscopyright(C)StanfordComputerScience,MartyStepp,VictoriaKirst,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

CS106B,Lecture11ExhaustiveSearchandBacktracking

Thisdocumentiscopyright(C)StanfordComputerScienceandAshleyTaylor,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyMartyStepp,ChrisGregg,KeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers

Page 2: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

2

Plan for Today • Newrecursiveproblem-solvingtechniques

–  ExhaustiveSearch–  Backtracking

Page 3: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

3

Exhaustive search • exhaustivesearch:Exploringeverypossiblecombinationfromasetofchoicesorvalues.–  oftenimplementedrecursively–  SometimescalledrecursiveenumerationApplications:–  producingallpermutationsofasetofvalues–  enumeratingallpossiblenames,passwords,etc.–  combinatoricsandlogicprogramming

• Oftenthesearchspaceconsistsofmanydecisions,eachofwhichhasseveralavailablechoices.–  Example:Whenenumeratingall5-letterstrings,eachofthe5lettersisadecision,andeachofthosedecisionshas26possiblechoices.

Page 4: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

4

Exhaustive search Ageneralpseudo-codealgorithmforexhaustivesearch:

Explore(decisions):

–  iftherearenomoredecisionstomake:Stop.

–  else,let'shandleonedecisionourselves,andtherestbyrecursion.foreachavailablechoiceCforthisdecision:• ChooseCbymodifyingparameters.• ExploretheremainingdecisionsthatcouldfollowC.• Un-chooseCbyreturningparameterstooriginalstate(ifnecessary).

Page 5: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

5

Exhaustive Search Model Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?The

iterationwillbedonebyrecursion.2.  Whatarethechoicesforeachdecision?Doweneedaforloop?

Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparameters?

a)  Doweneedtouseawrapperduetoextraparameters?

Un-Choosing4.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitly

un-modify,oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?

BaseCase5.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions?

Page 6: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

6

Exercise: printAllBinary • WritearecursivefunctionprintAllBinarythatacceptsanintegernumberofdigitsandprintsallbinarynumbersthathaveexactlythatmanydigits,inascendingorder,oneperline.

– printAllBinary(2); printAllBinary(3);

00 00001 00110 01011 011 100 101 110 111

printBinary

Page 7: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

7

printAllBinary Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?The

iterationwillbedonebyrecursion.2.  Whatarethechoicesforeachdecision?Doweneedaforloop?

Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparametersand

storeourpreviouschoices?a)  Doweneedtouseawrapperduetoextraparameters?

Un-Choosing4.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitly

un-modify,oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?

BaseCase5.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions?

Page 8: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

8

printAllBinary Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?Weare

iteratingovercharactersinthebinarystring2.  Whatarethechoicesforeachdecision?Doweneedaforloop?Choose0or1

Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparametersand

storeourpreviouschoices?Buildupastringthatwewilleventuallyprint.Addthe0or1toit.Stringtracksourpreviouschoicesa)  Doweneedtouseawrapperduetoextraparameters?Yes

Un-Choosing4.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitly

un-modify,oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?Ifnewstringsforeachcall,wedon'tneedtoun-choose

BaseCase5.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions?Printthe

string

Page 9: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

9

printAllBinary solution voidprintAllBinary(intnumDigits){printAllBinaryHelper(numDigits,"");}voidprintAllBinaryHelper(intdigits,stringsoFar){if(digits==0){cout<<soFar<<endl;}else{printAllBinaryHelper(digits-1,soFar+"0");printAllBinaryHelper(digits-1,soFar+"1");}}

Page 10: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

10

A tree of calls • printAllBinary(2);

–  Thiskindofdiagramiscalledacalltreeordecisiontree.–  Thinkofeachcallasachoiceordecisionmadebythealgorithm:

• ShouldIchoose0asthenextdigit?• ShouldIchoose1asthenextdigit?

digits soFar

2 ""

1 "0"

0 "00" 0 "01"

1 "1"

0 "10" 0 "11"

0 1

0 1 0 1

Page 11: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

11

The base case voidprintAllBinaryHelper(intdigits,stringsoFar){if(digits==0){cout<<soFar<<endl;}else{printAllBinaryHelper(digits-1,soFar+"0");printAllBinaryHelper(digits-1,soFar+"1");}}

–  Thebasecaseiswherethecodestopsafterdoingitswork.• pAB(3)->pAB(2)->pAB(1)->pAB(0)

–  Eachcallshouldkeeptrackoftheworkithasdone.

–  Basecaseshouldprinttheresultoftheworkdonebypriorcalls.• Workiskepttrackofinsomevariable(s)-inthiscase,stringsoFar.

Page 12: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

12

Exercise: printDecimal • WritearecursivefunctionprintDecimalthatacceptsanintegernumberofdigitsandprintsallbase-10numbersthathaveexactlythatmanydigits,inascendingorder,oneperline.

– printDecimal(2); printDecimal(3);

00 00001 00102 002.. ...98 99799 998 999

– Userecursion.*

printDecimal

Page 13: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

13

printDecimal Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?The

iterationwillbedonebyrecursion.2.  Whatarethechoicesforeachdecision?Doweneedaforloop?

Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparameters

storeourpreviouschoices?a)  Doweneedtouseawrapperduetoextraparameters?

Un-Choosing4.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitly

un-modify,oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?

BaseCase5.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions?

Page 14: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

14

printDecimal solution voidprintDecimal(intdigits){printDecimalHelper(digits,"");}voidprintDecimalHelper(intdigits,stringsoFar){if(digits==0){cout<<soFar<<endl;}else{for(inti=0;i<10;i++){printDecimalHelper(digits-1,soFar+integerToString(i));}}}

– Observation:Whenthesetofdigitchoicesavailableislarge,usingalooptoenumeratethemavoidsredundancy.(Thisisokay!)

– Note:Loopoverchoices,notdecisions

Page 15: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

15

Announcements

• Homework3dueonWednesdayat5PM• Shreyawillbeguest-lecturingonMonday

– Myofficehourswillbecancelledthatday(stillavailableviaemail)• MidtermReviewSessiononTuesday,July24,from7-9PMinGatesB01

Page 16: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

16

Backtracking • backtracking:Findingsolution(s)bytryingallpossiblepathsandthenabandoningthemiftheyarenotsuitable.

–  a"bruteforce"algorithmictechnique(triesallpaths)–  oftenimplementedrecursively–  Couldinvolvelookingforonesolution

• Ifanyofthepathsfoundasolution,asolutionexists!Ifnonefindasolution,nosolutionexists

–  Couldinvolvefindingallsolutions–  Idea:it'sexhaustivesearchwithconditionsApplications:–  parsinglanguages–  games:anagrams,crosswords,wordjumbles,8queens,sudoku–  combinatoricsandlogicprogramming–  escapingfromamaze

Page 17: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

17

Backtracking: One Solution Ageneralpseudo-codealgorithmforbacktrackingproblems

searchingforonesolutionBacktrack(decisions):

–  iftherearenomoredecisionstomake:• ifourcurrentsolutionisvalid,returntrue• else,returnfalse

–  else,let'shandleonedecisionourselves,andtherestbyrecursion.foreachavailablevalidchoiceCforthisdecision:• ChooseCbymodifyingparameters.• ExploretheremainingdecisionsthatcouldfollowC.Ifanyofthemfindasolution,returntrue

• Un-chooseCbyreturningparameterstooriginalstate(ifnecessary).–  Ifnosolutionswerefound,returnfalse

Page 18: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

18

Backtracking: All Solutions Ageneralpseudo-codealgorithmforbacktrackingproblems

searchingforallsolutionsBacktrack(decisions):

–  iftherearenomoredecisionstomake:• ifourcurrentsolutionisvalid,addittoourlistoffoundsolutions• else,donothingorreturn

–  else,let'shandleonedecisionourselves,andtherestbyrecursion.foreachavailablevalidchoiceCforthisdecision:• ChooseCbymodifyingparameters.• ExploretheremainingdecisionsthatcouldfollowC.Keeptrackofwhichsolutionstherecursivecallsfind.

• Un-chooseCbyreturningparameterstooriginalstate(ifnecessary).–  Returnthelistofsolutionsfoundbyallthehelperrecursivecalls.

Page 19: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

19

Backtracking Model Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?Whatarethe

choicesforeachdecision?Doweneedaforloop?Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparametersandstore

ourpreviouschoices(avoidingarms-lengthrecursion)?a)  Doweneedtouseawrapperduetoextraparameters?

4.  Howshouldwerestrictourchoicestobevalid?5.  Howshouldweusethereturnvalueoftherecursivecalls?Arewelookingforall

solutionsorjustone?Un-choosing6.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitlyun-modify,

oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?BaseCase7.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions(usuallyreturntrue)?8.  Isthereacaseforwhentherearen'tanyvalidchoicesleftora"bad"stateisreached

(usuallyreturnfalse)?9.  Arethebasecasesorderedproperly?Areweavoidingarms-lengthrecursion?

Page 20: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

20

Exercise: Dice roll sum • WriteafunctiondiceSumthatacceptstwointegerparameters:anumberofdicetoroll,andadesiredsumofalldievalues.Outputallcombinationsofdievaluesthatadduptoexactlythatsum.

diceSum(2,7); diceSum(3,7); {1,1,5}

{1,2,4}{1,3,3}{1,4,2}{1,5,1}{2,1,4}{2,2,3}{2,3,2}{2,4,1}{3,1,3}{3,2,2}{3,3,1}{4,1,2}{4,2,1}{5,1,1}

{1,6}{2,5}{3,4}{4,3}{5,2}{6,1}

diceSum

Page 21: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

21

Dice Roll Sum Choosing1.  Wegenerallyiterateoverdecisions.Whatareweiteratingoverhere?Whatarethe

choicesforeachdecision?Doweneedaforloop?Exploring3.  Howcanwerepresentthatchoice?Howshouldwemodifytheparametersandstore

ourpreviouschoices(avoidingarms-lengthrecursion)?a)  Doweneedtouseawrapperduetoextraparameters?

4.  Howshouldwerestrictourchoicestobevalid?5.  Howshouldweusethereturnvalueoftherecursivecalls?Arewelookingforall

solutionsorjustone?Un-choosing6.  Howdoweun-modifytheparametersfromstep3?Doweneedtoexplicitlyun-modify,

oraretheycopied?Aretheyun-modifiedatthesamelevelastheyweremodified?BaseCase7.  Whatshouldwedointhebasecasewhenwe'reoutofdecisions(usuallyreturntrue)?8.  Isthereacaseforwhentherearen'tanyvalidchoicesleftora"bad"stateisreached

(usuallyreturnfalse)?9.  Arethebasecasesorderedproperly?Areweavoidingarms-lengthrecursion?

Page 22: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

22

Easier: Dice rolls • Suggestion:Firstjustoutputallpossiblecombinationsofvaluesthatcouldappearonthedice.

• Thisisjustexhaustivesearch!•  Ingeneral,startingwithexhaustivesearchandthenaddingconditionsisnotabadidea

diceSum(2,7); diceSum(3,7);

{1,1}{1,2}{1,3}{1,4}{1,5}{1,6}{2,1}{2,2}{2,3}{2,4}{2,5}{2,6}

{3,1}{3,2}{3,3}{3,4}{3,5}{3,6}{4,1}{4,2}{4,3}{4,4}{4,5}{4,6}

{5,1}{5,2}{5,3}{5,4}{5,5}{5,6}{6,1}{6,2}{6,3}{6,4}{6,5}{6,6}

{1,1,1}{1,1,2}{1,1,3}{1,1,4}{1,1,5}{1,1,6}{1,2,1}{1,2,2}...{6,6,4}{6,6,5}{6,6,6}

diceRoll

Page 23: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

23

A decision tree chosen available

- 4dice

1 3dice

1,1 2dice

1,1,1 1die

1,1,1,1

1,2 2dice 1,3 2dice 1,4 2dice

2 3dice

1,1,2 1die 1,1,3 1die

1,1,1,2 1,1,3,1 1,1,3,2

1,4,1 1die ... ... ...

...

... ... ... ...

valueforfirstdie?

valueforseconddie?

valueforthirddie?

diceSum(4,7);

Page 24: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

24

Initial solution voiddiceSum(intdice,intdesiredSum){Vector<int>chosen;diceSumHelper(dice,desiredSum,chosen);}voiddiceSumHelper(intdice,intdesiredSum,Vector<int>&chosen){if(dice==0){if(sumAll(chosen)==desiredSum){cout<<chosen<<endl;//basecase}}else{for(inti=1;i<=6;i++){chosen.add(i);//choosediceSumHelper(dice-1,desiredSum,chosen);//explorechosen.remove(chosen.size()-1);//un-choose}}}intsumAll(constVector<int>&v){//addsthevaluesingivenvectorintsum=0;for(intk:v){sum+=k;}returnsum;}

Page 25: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

25

Wasteful decision tree chosen available desiredsum

- 3dice 5

1 2dice

1,1 1die

1,1,1

1,2 1die 1,3 1die 1,4 1die

6 2dice

...

2 2dice 3 2dice 4 2dice 5 2dice

1,5 1die 1,6 1die

1,1,2 1,1,3 1,1,4 1,1,5 1,1,6

1,6,1 1,6,2

...

diceSum(3,5);

Page 26: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

26

Optimizations • Weneednotvisiteverybranchofthedecisiontree.

–  Somebranchesareclearlynotgoingtoleadtosuccess.– Wecanpreemptivelystop,orprune,thesebranches.

•  Inefficienciesinourdicesumalgorithm:–  Sometimesthecurrentsumisalreadytoohigh.

• (Evenrolling1forallremainingdicewouldexceedthedesiredsum.)

–  Sometimesthecurrentsumisalreadytoolow.• (Evenrolling6forallremainingdicewouldexceedthedesiredsum.)

–  Thecodemustre-computethesummanytimes.• (1+1+1=...,1+1+2=...,1+1+3=...,1+1+4=...,...)

Page 27: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

27

diceSum solution voiddiceSum(intdice,intdesiredSum){Vector<int>chosen;diceSumHelper(dice,0,desiredSum,chosen);}voiddiceSumHelper(intdice,intsum,intdesiredSum,Vector<int>&chosen){if(dice==0){if(sum==desiredSum){cout<<chosen<<endl;//solutionfoundbasecase}}elseif(sum+1*dice>desiredSum//invalidstatebasecase||sum+6*dice<desiredSum){return;}else{for(inti=1;i<=6;i++){chosen.add(i);//choosediceSumHelper(dice-1,sum+i,desiredSum,chosen);//explorechosen.remove(chosen.size()-1);//un-choose}}}

Page 28: CS 106B, Lecture 11 Exhaustive Search and Backtracking file1. We generally iterate over decisions. What are we iterating over here? The iteration will be done by recursion. 2. What

28

A Twist • HowwouldyoumodifydiceSumsothatitprintsonlyuniquecombinationsofdice,ignoringorder?–  (e.g.don'tprintboth{1,1,5}and{1,5,1})

diceSum2(2,7); diceSum2(3,7);

{1,1,5}{1,2,4}{1,3,3}{1,4,2}{1,5,1}{2,1,4}{2,2,3}{2,3,2}{2,4,1}{3,1,3}{3,2,2}{3,3,1}{4,1,2}{4,2,1}{5,1,1}

{1,6}{2,5}{3,4}{4,3}{5,2}{6,1}