forked from anish2210/hacktober2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NKnight.java
62 lines (55 loc) · 1.75 KB
/
NKnight.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
import java.util.Arrays;
public class NKnight {
public static void main(String[] args) {
boolean[][] board = new boolean[4][4];
int[][] state = new int[4][4];
nKnight(3, board, 0, 0, state);
}
static void nKnight(int knight, boolean[][] board, int r, int c, int[][] state) {
if (knight == 0) {
for (int[] is : state) {
System.out.println(Arrays.toString(is));
}
System.out.println();
return;
}
if (r >= board.length - 1 && c >= board[r].length - 1) {
return;
}
if (c > board[r].length - 1) {
nKnight(knight, board, r + 1, 0, state);
return;
}
if (isSafe(board, r, c)) {
board[r][c] = true;
state[r][c] = 1;
nKnight(knight - 1, board, r, c + 1, state);
board[r][c] = false;
state[r][c] = 0;
}
nKnight(knight, board, r, c + 1, state);
}
// check for the place
private static boolean isSafe(boolean[][] board, int r, int c) {
if (isValid(board, r - 2, c - 1) && board[r - 2][c - 1]) {
return false;
}
if (isValid(board, r - 2, c + 1) && board[r - 2][c + 1]) {
return false;
}
if (isValid(board, r - 1, c - 2) && board[r - 1][c - 2]) {
return false;
}
if (isValid(board, r - 1, c + 2) && board[r - 1][c + 2]) {
return false;
}
return true;
}
// checks for values are not out of bound
static boolean isValid(boolean[][] board, int r, int c) {
if (r >= 0 && r < board.length && c >= 0 && c < board[r].length) {
return true;
}
return false;
}
}