The Knight's Tour Problem
The Knight's Tour Problem
IDE
Q&A
GeeksQuiz
Acomputerscienceportalforgeeks
Backtracking|Set1(TheKnightstourproblem)
Backtrackingisanalgorithmicparadigmthattriesdifferentsolutionsuntilfindsasolutionthatworks.Problems
whicharetypicallysolvedusingbacktrackingtechniquehavefollowingpropertyincommon.Theseproblems
canonlybesolvedbytryingeverypossibleconfigurationandeachconfigurationistriedonlyonce.ANaive
solutionfortheseproblemsistotryallconfigurationsandoutputaconfigurationthatfollowsgivenproblem
constraints.BacktrackingworksinincrementalwayandisanoptimizationovertheNaivesolutionwhereall
possibleconfigurationsaregeneratedandtried.
Forexample,considerthefollowingKnightsTourproblem.
Theknightisplacedonthefirstblockofanemptyboardand,movingaccordingtotherulesofchess,mustvisit
eachsquareexactlyonce.
LetusfirstdiscusstheNaivealgorithmforthisproblemandthentheBacktrackingalgorithm.
NaiveAlgorithmforKnightstour
TheNaiveAlgorithmistogeneratealltoursonebyoneandcheckifthegeneratedtoursatisfiestheconstraints.
whilethereareuntriedtours
{
generatethenexttour
ifthistourcoversallsquares
{
printthispath;
}
}
Backtrackingworksinanincrementalwaytoattackproblems.Typically,westartfromanemptysolutionvector
andonebyoneadditems(Meaningofitemvariesfromproblemtoproblem.IncontextofKnightstourproblem,
anitemisaKnightsmove).Whenweaddanitem,wecheckifaddingthecurrentitemviolatestheproblem
constraint,ifitdoesthenweremovetheitemandtryotheralternatives.Ifnoneofthealternativesworkoutthen
wegotopreviousstageandremovetheitemaddedinthepreviousstage.Ifwereachtheinitialstageback
thenwesaythatnosolutionexists.Ifaddinganitemdoesntviolateconstraintsthenwerecursivelyadditems
onebyone.Ifthesolutionvectorbecomescompletethenweprintthesolution.
BacktrackingAlgorithmforKnightstour
FollowingistheBacktrackingalgorithmforKnightstourproblem.
Ifallsquaresarevisited
printthesolution
Else
a)Addoneofthenextmovestosolutionvectorandrecursively
checkifthismoveleadstoasolution.(AKnightcanmakemaximum
eightmoves.Wechooseoneofthe8movesinthisstep).
b)Ifthemovechosenintheabovestepdoesn'tleadtoasolution
thenremovethismovefromthesolutionvectorandtryother
alternativemoves.
c)Ifnoneofthealternativesworkthenreturnfalse(Returningfalse
willremovethepreviouslyaddediteminrecursionandiffalseis
returnedbytheinitialcallofrecursionthen"nosolutionexists")
FollowingisCimplementationforKnightstourproblem.Itprintsoneofthepossiblesolutionsin2Dmatrixform.
Basically,theoutputisa2D8*8matrixwithnumbersfrom0to63andthesenumbersshowstepsmadeby
Knight.
#include<stdio.h>
#defineN8
intsolveKTUtil(intx,inty,intmovei,intsol[N][N],intxMove[],
intyMove[]);
/*Autilityfunctiontocheckifi,jarevalidindexesforN*Nchessboard*/
intisSafe(intx,inty,intsol[N][N])
{
if(x>=0&&x<N&&y>=0&&y<N&&sol[x][y]==1)
return1;
return0;
}
/*Autilityfunctiontoprintsolutionmatrixsol[N][N]*/
voidprintSolution(intsol[N][N])
{
for(intx=0;x<N;x++)
{
for(inty=0;y<N;y++)
printf("%2d",sol[x][y]);
printf("\n");
}
}
/*ThisfunctionsolvestheKnightTourproblemusingBacktracking.This
functionmainlyusessolveKTUtil()tosolvetheproblem.Itreturnsfalseif
nocompletetourispossible,otherwisereturntrueandprintsthetour.
Pleasenotethattheremaybemorethanonesolutions,thisfunction
printsoneofthefeasiblesolutions.*/
boolsolveKT()
{
intsol[N][N];
/*Initializationofsolutionmatrix*/
for(intx=0;x<N;x++)
for(inty=0;y<N;y++)
sol[x][y]=1;
/*xMove[]andyMove[]definenextmoveofKnight.
xMove[]isfornextvalueofxcoordinate
yMove[]isfornextvalueofycoordinate*/
intxMove[8]={2,1,1,2,2,1,1,2};
intyMove[8]={1,2,2,1,1,2,2,1};
//SincetheKnightisinitiallyatthefirstblock
sol[0][0]=0;
/*Startfrom0,0andexplorealltoursusingsolveKTUtil()*/
if(solveKTUtil(0,0,1,sol,xMove,yMove)==false)
{
printf("Solutiondoesnotexist");
returnfalse;
}
else
printSolution(sol);
returntrue;
}
/*ArecursiveutilityfunctiontosolveKnightTourproblem*/
intsolveKTUtil(intx,inty,intmovei,intsol[N][N],intxMove[N],
intyMove[N])
{
intk,next_x,next_y;
if(movei==N*N)
returntrue;
/*Tryallnextmovesfromthecurrentcoordinatex,y*/
for(k=0;k<8;k++)
{
next_x=x+xMove[k];
next_y=y+yMove[k];
if(isSafe(next_x,next_y,sol))
{
sol[next_x][next_y]=movei;
if(solveKTUtil(next_x,next_y,movei+1,sol,xMove,yMove)==true)
returntrue;
else
sol[next_x][next_y]=1;//backtracking
}
}
returnfalse;
}
/*Driverprogramtotestabovefunctions*/
intmain()
{
solveKT();
getchar();
return0;
}
Output:
05938333017863
373431609622916
58136393227187
3548412661101528
42572494023619
4750455425201114
56435232213245
514655445342112
NotethatBacktrackingisnotthebestsolutionfortheKnightstourproblem.Seethisforotherbettersolutions.
ThepurposeofthispostistoexplainBacktrackingwithanexample.
References:
http://see.stanford.edu/materials/icspacs106b/H19RecBacktrackExamples.pdf
http://www.cis.upenn.edu/~matuszek/cit5942009/Lectures/35backtracking.ppt
http://mathworld.wolfram.com/KnightsTour.html
http://en.wikipedia.org/wiki/Knight%27s_tour
Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopic
discussedabove.
RelatedPosts:
GeneratePythagoreanTriplets
Squarerootofaninteger
Findminimumtimetofinishalljobswithgivenconstraints
Findnumberofsolutionsofalinearequationofnvariables
Sortastackusingrecursion
Lengthofthelongestvalidsubstring
Worms,Virusesandbeyond!!
Countnumberofwaystocoveradistance
Like
28
Tweet
Writingcodeincomment?Pleaseusecode.geeksforgeeks.org,generatelinkandsharethelinkhere.
@geeksforgeeks,SomerightsreservedContactUs!AboutUs!Advertisewithus!