forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNKnight.java
More file actions
91 lines (90 loc) · 2.08 KB
/
Copy pathNKnight.java
File metadata and controls
91 lines (90 loc) · 2.08 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
package com.dsa;
public class NKnight {
public static void main(String[] args) {
int n=4;
boolean[][] board = new boolean[n][n];
knight(board,0,0,4);
}
static void knight(boolean[][]board,int row,int col,int knights)
{
if(knights==0)
{
display(board);
System.out.println();
return;
}
if(row==board.length-1 && col==board.length)
{
return;
}
if(col==board.length)
{
knight(board,row+1,0,knights);
return;
}
if(isSafe(board,row,col))
{
board[row][col]=true;
knight(board,row,col+1,knights-1);
board[row][col]=false;
}
knight(board,row,col+1,knights);
}
static boolean isSafe(boolean[][] board,int row, int col)
{
if(isValid(board,row-2,col+1))
{
if(board[row-2][col+1])
{
return false;
}
}
if(isValid(board,row-2,col-1))
{
if(board[row-2][col-1])
{
return false;
}
}
if(isValid(board,row-1,col+2))
{
if(board[row-1][col+2])
{
return false;
}
}
if(isValid(board,row-1,col-2))
{
if(board[row-1][col-2])
{
return false;
}
}
return true;
}
static boolean isValid(boolean[][] board,int row, int col)
{
if(row>=0 && row<board.length && col>=0 && col<board.length)
{
return true;
}
return false;
}
static void display(boolean[][] board)
{
for(boolean[] row : board)
{
for (boolean element : row)
{
if(element)
{
System.out.print("K ");
}
else{
System.out.print("X ");
}
}
System.out.println();
}
}
}