forked from Shubhamlmp/Programming-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnight.java
66 lines (61 loc) · 2.1 KB
/
Knight.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Knight {
static PrintWriter out = new PrintWriter(System.out);
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
FastScanner scn = new FastScanner();
int [][]chess = new int[5][5];
printKnightTour(chess,0,0,0);
out.close();
}
public static void printKnightTour(int[][]chess,int r,int c,int move){
if(r<0||c<0||r>=chess.length||c>= chess.length||chess[r][c] > 0){
return;
}
else if(move == (chess.length * chess.length) - 1){
chess[r][c] = move;
displayBoard(chess);
chess[r][c] = 0;
return;
}
chess[r][c] = move;
printKnightTour(chess,r-2,c+1,move+1);
printKnightTour(chess,r-1,c+2,move+1);
printKnightTour(chess,r+1,c+2,move+1);
printKnightTour(chess,r+2,c+1,move+1);
printKnightTour(chess,r+2,c-1,move+1);
printKnightTour(chess,r+1,c-2,move+1);
printKnightTour(chess,r-1,c-2,move+1);
printKnightTour(chess,r-2,c-1,move+1);
chess[r][c] = 0;
}
public static void displayBoard(int [][]chess){
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess.length; j++) {
System.out.print(chess[i][j] + " ");
}
System.out.println();
}
}
}