1111 * @date: 10/15/15
1212 * @time: 11:56 PM
1313 * @see: https://en.wikipedia.org/wiki/Knight%27s_tour
14+ * @see: me.ramswaroop.backtracking.RatInAMaze for a simpler version of this problem
1415 */
1516public class KnightTour {
1617
1718 /**
18- * @param i
19- * @param j
19+ * Determines if a move is a valid move in the given chess board.
20+ *
21+ * @param i is the row of the new move
22+ * @param j is the column of the new move
2023 * @param tour
2124 * @return
2225 */
@@ -29,6 +32,9 @@ public static boolean isValidMove(int i, int j, int[][] tour) {
2932 }
3033
3134 /**
35+ * Finds a valid knight's tour for a given chess board size if any
36+ * with the use of backtracking.
37+ *
3238 * @param i
3339 * @param j
3440 * @param xMoves
@@ -44,35 +50,45 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves
4450 int nextI , nextJ ;
4551
4652 for (int k = 0 ; k < xMoves .length ; k ++) {
53+ // next move is calculated from all possible moves
4754 nextI = i + xMoves [k ];
4855 nextJ = j + yMoves [k ];
4956
57+ // if the next move is valid then we proceed otherwise we
58+ // try next set of moves
5059 if (isValidMove (nextI , nextJ , tour )) {
5160 tour [nextI ][nextJ ] = step ;
5261 if (isValidKnightTour (nextI , nextJ , xMoves , yMoves , step + 1 , tour )) {
5362 return true ;
5463 } else {
55- tour [nextI ][nextJ ] = 0 ;
64+ tour [nextI ][nextJ ] = 0 ; // backtrack
5665 }
5766 }
5867 }
5968
6069 return false ;
6170 }
6271
72+
6373 /**
64- * @param boardSize
74+ * Prints the knight's tour if any.
75+ *
76+ * @param i is the start row
77+ * @param j is the start column
78+ * @param boardSize is the size of the chess board
6579 */
66- public static void printKnightTour (int [] boardSize ) {
80+ public static void printKnightTour (int i , int j , int [] boardSize ) {
6781 if (boardSize .length < 2 ) return ;
6882
83+ // a 2D array for the knight's tour
6984 int [][] tour = new int [boardSize [0 ]][boardSize [1 ]];
85+ // all possible relative moves that a knight can make
7086 int [] xMoves = new int []{1 , 1 , 2 , 2 , -1 , -1 , -2 , -2 };
7187 int [] yMoves = new int []{-2 , 2 , -1 , 1 , -2 , 2 , -1 , 1 };
7288
7389 tour [0 ][0 ] = 1 ;
7490
75- if (isValidKnightTour (0 , 0 , xMoves , yMoves , 2 , tour )) {
91+ if (isValidKnightTour (i , j , xMoves , yMoves , 2 , tour )) {
7692 print2DMatrix (tour );
7793 } else {
7894 System .out .println ("Knight's tour doesn't exist for board size [" + boardSize [0 ] + "x" + boardSize [1 ] + "]" );
@@ -90,6 +106,6 @@ public static void print2DMatrix(int[][] array) {
90106 }
91107
92108 public static void main (String a []) {
93- printKnightTour (new int []{8 , 8 });
109+ printKnightTour (0 , 0 , new int []{8 , 8 });
94110 }
95111}
0 commit comments