Knight’s Tour | Matlab Examples

Matlab Tutorials | Examples

Practice 14:

Knight’s Tour (Advance)

One of the interesting puzzles for chess buffs is the Knight’s Tour problem, which is attributed to the famous mathematician Euler. The question is this: Can the chess piece called the knight move around an empty chessboard and land in each of the 64 squares once and only once?
The knight, symbolized by a horse figure in chess, makes L-shaped moves: It goes two places horizontally or vertically, and one place in a direction perpendicular to the initial one. Thus, from a square in the middle of an empty chessboard, a knight can make eight different moves. However, at the sides of the board, or even more at the corners, the alternative moves a knight can make are much more limited (see the black and white knights in the picture).
Write a MATLAB program that will do the following:
a) Create an 8×8 matrix for keeping track of the visited and non-visited squares of a chess board. Unvisited squares should have a value of zero.
b) Randomly initialize the knight into one of the squares on the board.
c) If there are unvisited square(s) the knight can move to, randomly choose one of those, and move the knight to the chosen square. Add the address of this square into an array for later printing. Keep repeating (c).
d) When there are no unvisited squares the knight can move to, check the number of squares that were visited. If the count is greater than or equal to 60, print all the moves of the knight (the list of squares in their visit order) into a file named KnightsTour.txt. The list for the sequence of moves should be printed on a single line. The line should contain the iteration number and the number of squares that were visited.
e) Unless all 64 squares are visited, repeat the program from (a).
This program may take many hours and many thousands of iterations. Note that due to the random nature of iterations, there is no predefined single output.




2 thoughts on “Knight’s Tour | Matlab Examples

  1. i am doing image encryption
    where i divide the image 256*256(65536 pixels) into 8*8 matrices can i use your code and can i apply for each matrix is it possible or there is any way to do it(to apply knights tour on any 8*8 matrix like that i have to do for 1024 matrices to complete 256*256 matrix)

Leave a Reply

Your email address will not be published. Required fields are marked *