0% found this document useful (0 votes)
165 views5 pages

The Knight's Tour Problem

The document discusses backtracking as an algorithmic paradigm to solve problems by trying different solutions incrementally until finding one that works. It provides the example of solving the Knight's tour problem, where a knight must visit every square on a chessboard exactly once. First, it explains a naive algorithm to generate and check all possible tours. Then, it describes the backtracking algorithm, which starts with an empty solution and incrementally adds moves, checking at each step if the partial solution violates constraints before continuing. Finally, it provides C code implementing the backtracking algorithm to solve the Knight's tour problem and print one possible solution.

Uploaded by

Amit Anand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views5 pages

The Knight's Tour Problem

The document discusses backtracking as an algorithmic paradigm to solve problems by trying different solutions incrementally until finding one that works. It provides the example of solving the Knight's tour problem, where a knight must visit every square on a chessboard exactly once. First, it explains a naive algorithm to generate and check all possible tours. Then, it describes the backtracking algorithm, which starts with an empty solution and incrementally adds moves, checking at each step if the partial solution violates constraints before continuing. Finally, it provides C code implementing the backtracking algorithm to solve the Knight's tour problem and print one possible solution.

Uploaded by

Amit Anand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

GeeksforGeeks

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.

75Comments Category: Misc Tags: Backtracking

RelatedPosts:
GeneratePythagoreanTriplets
Squarerootofaninteger
Findminimumtimetofinishalljobswithgivenconstraints
Findnumberofsolutionsofalinearequationofnvariables
Sortastackusingrecursion
Lengthofthelongestvalidsubstring

Worms,Virusesandbeyond!!
Countnumberofwaystocoveradistance

Like

28

Tweet

Writingcodeincomment?Pleaseusecode.geeksforgeeks.org,generatelinkandsharethelinkhere.

@geeksforgeeks,SomerightsreservedContactUs!AboutUs!Advertisewithus!

You might also like