-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathNKnightKill.java
More file actions
104 lines (80 loc) · 2.03 KB
/
NKnightKill.java
File metadata and controls
104 lines (80 loc) · 2.03 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
It is a backtracking problem in which there are N knights
that need to be placed on an N*N board in such a manner so
that no two knights can kill each other.
The code will display all the possible positions of Knights
where - will represent a blank box and
X will represent a Knight in a box.
*/
import java.util.Scanner;
public class NKnightKill {
private static void display(char[][] board) {
for (int i=0; i<board.length; i++) {
for (int j=0; j<board.length; j++) {
System.out.print (board[i][j]+"\t");
}
System.out.println();
}
}
private static boolean isSafe(char[][] board, int i, int j) {
// function will check if is it safe to
// place the Knight at i,j
if (i-2>=0 && j-1>=0 && board[i-2][j-1]=='X') {
return false;
}
if (i-2>=0 && j+1<board.length && board[i-2][j+1]=='X') {
return false;
}
if (i-1>=0 && j-2>=0 && board[i-1][j-2]=='X') {
return false;
}
if (i-1>=0 && j+2<board.length && board[i-1][j+2]=='X') {
return false;
}
return true;
}
private static void nKnight(char[][] board, int i, int j, int n) {
if (n==0) {
System.out.println("Possibility "+count+" - ");
display (board);
count++;
System.out.println();
return;
} else if (i==board.length) {
return;
} else if (j==board.length) {
nKnight(board, i+1, 0, n);
} else {
if (isSafe(board,i,j)) {
board[i][j]='X';
nKnight(board, i, j+1, n-1);
board[i][j]='-';
}
nKnight(board, i, j+1, n);
}
}
static int count = 1;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print ("Enter no. of Knights / board size - ");
int n=sc.nextInt();
char[][] board=new char[n][n];
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
board[i][j]='-';
}
}
nKnight(board,0,0,n);
}
}
/**
Time Complexity : O(2^(N*N))
Space Complexity : O(N*N)
Input:
Enter no. of Knights / board size - 3
Output (Many boards are possible therefore showing only one):
Possibility 1 -
X X X
- - -
- - -
*/