Академический Документы
Профессиональный Документы
Культура Документы
Backtracking: Introduction
CPSC 490
Backtracking: Introduction
thebigOnotationdoesnotgiveenoughinformation.Armedwiththislittletool,let'slookatafew techniquesforapplyingbruteforcetooneclassicproblem.
Backtracking: Introduction
introw[8],used[8]; intqueens(inti){ if(i==8){ //Placedall8queens.Verifydiagonals. for(intj=0;j<8;j++) for(intk=j+1;k<8;k++){ if(row[j]+j==row[k]+k)return0; if(row[j]j==row[k]k)return0; } return1; } inttotal=0; for(row[i]=0;row[i]<8;row[i]++) { //ensurewearenotsharingarow if(used[row[i]])continue; //placethequeenandrecurseontherest used[row[i]]=true; total+=queens(i+1); //marktherowasunusedagain used[row[i]]=false; } returntotal; }
Tousethefunctionqueens(),firstclearused[]tobeallfalseandthencallqueens(0).row[i]isthe rowinwhichqueenincolumniresides.used[r]istrueifsomequeenwehavealreadyplacedusesrow r.Onceireaches8,weverifythatnotwoqueensshareadiagonalandreturn1.queens(0)finishesin about30millisecondsandreturns92.That'squiteanimprovement. Youmayhavenoticedthatweareessentiallygeneratingallthe8!permutationswiththisfunction. Theexactnumberofoperationsrequiredisabout20million(8!*8*36)thereare8!recursivecalls, eachonerequiring8iterationsoftheloop,and36operationstocheckforavalidconfiguration.This canalsobedonewithoutanyrecursion,simplyusingnext_permutation(). NotehowsimilarthisimplementationistoDFS.Ifweconsidereachpartialconfiguration(whereonly thefirstiqueenshavebeenassignedrows)avertex,thenweadoingadepthfirstsearchonacertain configurationgraph.ItisusefultothinkofbacktrackingasgraphsearchorDFSbecausewewillbe abletoapplysomeoftheideasfromgraphtheoryhere.Forinstance,thinkaboutwhatitwouldmean touseBFSinthiscaseinsteadofDFS.Whichwayismoreefficient?Wewillcomebacktothisidea later. Itmayseemlikeawastetoexplore8!(40320)configurationsjusttofindthe92thatwearelooking for.Ifweincreasethesizeoftheboardto10x10,theprogramwillrequireabout5seconds.Fora 13x13board,Iwaitedforhalfandhourforittofinishandgaveup.Inthenextsectionwewillseeone veryusefultechniquethatwillallowustoimprovethealgorithmsothatitworksonlargerboard sizes.Formoreinfoonthisclassicproblem,see http://www.research.att.com/cgibin/access.cgi/as/njas/sequences/eisA.cgi?Anum=A000170