-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpringer.java
More file actions
57 lines (49 loc) · 1.47 KB
/
Springer.java
File metadata and controls
57 lines (49 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Knight's tour backtracking
*/
public final class Springer {
public static int[][] moves = { { -2, -1 }, { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 },
{ -1, -2 } };
private static boolean solved(boolean[][] board) {
return solved(board, 0, 0, 0);
}
private static boolean solved(boolean[][] board, int step, int row, int col) {
if (step == (board.length * board.length) - 1) {
return true;
} else {
boolean found = false;
int direction = 0;
while (direction < 8 && !found) {
if (canMove(board, direction, row, col)) {
row += moves[direction][0];
col += moves[direction][1];
board[row][col] = true;
found = solved(board, step + 1, row, col);
if (!found) {
board[row][col] = false;
row -= moves[direction][0];
col -= moves[direction][1];
}
}
direction++;
}
return found;
}
}
private static boolean canMove(boolean[][] board, int direction, int row, int col) {
row += moves[direction][0];
col += moves[direction][1];
if(row < 0 || row >= board.length || col < 0 || col >= board.length || board[row][col] == true ) return false;
else return true;
}
public static void main(String[] args) {
final int N = 7;
boolean[][] board = new boolean[N][N];
if (solved(board)) {
BoardPrinter.print(board);
} else {
System.err.println("No solution found for N = " + N);
BoardPrinter.print(board);
}
}
}