-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathKnightsTour.java
39 lines (33 loc) · 1.33 KB
/
KnightsTour.java
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
public class Main {
public static void main(String args[]) {
int board[][] = new int [8][8];
knighttour(board, 0, 0, 1);
}
static void display(int board[][]) {
for (int x = 0; x < board.length; x++) {
for (int y = 0; y < board.length; y++)
System.out.print(board[x][y] + " ");
System.out.println();
}
}
static boolean knighttour(int board[][], int r, int c, int move) {
if(r < 0 || c < 0 || r >= board.length || c >= board.length || board[r][c] > 0) return false;
else if(move == board.length * board.length) {
board[r][c] = move;
display(board);
board[r][c] = 0;
return true;
}
board[r][c] = move;
if(knighttour(board, r-2, c+1, move+1)) return true;
else if(knighttour(board, r-1, c+2, move+1)) return true;
else if(knighttour(board, r+1, c+2, move+1)) return true;
else if(knighttour(board, r+2, c+1, move+1)) return true;
else if(knighttour(board, r+2, c-1, move+1)) return true;
else if(knighttour(board, r+1, c-2, move+1)) return true;
else if(knighttour(board, r-1, c-2, move+1)) return true;
else if(knighttour(board, r-2, c-1, move+1)) return true;
board[r][c] = 0;
return false;
}
}