11
11
* @date: 10/15/15
12
12
* @time: 11:56 PM
13
13
* @see: https://en.wikipedia.org/wiki/Knight%27s_tour
14
+ * @see: me.ramswaroop.backtracking.RatInAMaze for a simpler version of this problem
14
15
*/
15
16
public class KnightTour {
16
17
17
18
/**
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
20
23
* @param tour
21
24
* @return
22
25
*/
@@ -29,6 +32,9 @@ public static boolean isValidMove(int i, int j, int[][] tour) {
29
32
}
30
33
31
34
/**
35
+ * Finds a valid knight's tour for a given chess board size if any
36
+ * with the use of backtracking.
37
+ *
32
38
* @param i
33
39
* @param j
34
40
* @param xMoves
@@ -44,35 +50,45 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves
44
50
int nextI , nextJ ;
45
51
46
52
for (int k = 0 ; k < xMoves .length ; k ++) {
53
+ // next move is calculated from all possible moves
47
54
nextI = i + xMoves [k ];
48
55
nextJ = j + yMoves [k ];
49
56
57
+ // if the next move is valid then we proceed otherwise we
58
+ // try next set of moves
50
59
if (isValidMove (nextI , nextJ , tour )) {
51
60
tour [nextI ][nextJ ] = step ;
52
61
if (isValidKnightTour (nextI , nextJ , xMoves , yMoves , step + 1 , tour )) {
53
62
return true ;
54
63
} else {
55
- tour [nextI ][nextJ ] = 0 ;
64
+ tour [nextI ][nextJ ] = 0 ; // backtrack
56
65
}
57
66
}
58
67
}
59
68
60
69
return false ;
61
70
}
62
71
72
+
63
73
/**
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
65
79
*/
66
- public static void printKnightTour (int [] boardSize ) {
80
+ public static void printKnightTour (int i , int j , int [] boardSize ) {
67
81
if (boardSize .length < 2 ) return ;
68
82
83
+ // a 2D array for the knight's tour
69
84
int [][] tour = new int [boardSize [0 ]][boardSize [1 ]];
85
+ // all possible relative moves that a knight can make
70
86
int [] xMoves = new int []{1 , 1 , 2 , 2 , -1 , -1 , -2 , -2 };
71
87
int [] yMoves = new int []{-2 , 2 , -1 , 1 , -2 , 2 , -1 , 1 };
72
88
73
89
tour [0 ][0 ] = 1 ;
74
90
75
- if (isValidKnightTour (0 , 0 , xMoves , yMoves , 2 , tour )) {
91
+ if (isValidKnightTour (i , j , xMoves , yMoves , 2 , tour )) {
76
92
print2DMatrix (tour );
77
93
} else {
78
94
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) {
90
106
}
91
107
92
108
public static void main (String a []) {
93
- printKnightTour (new int []{8 , 8 });
109
+ printKnightTour (0 , 0 , new int []{8 , 8 });
94
110
}
95
111
}
0 commit comments