forked from sunidhi2001/Hacktoberfest2022-accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NxN_KillChessBoardQueen.java
90 lines (81 loc) · 1.62 KB
/
NxN_KillChessBoardQueen.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package Backtracking;
public class NxN_KillChessBoardQueen { public static void main(String[] args) {
// TODO Auto-generated method stub
NQueen2DKill(new boolean[4][4],4,0,0,0,"");
}
public static void NQueen2DKill(boolean[][] board,int tq,int qpsf,int col,int row,String ans)
{
//Positive Base Case
if(qpsf==tq)
{
System.out.println(ans);
return;
}
//Either use line 21-24 OR line 27-31
//Manually changing row
if(col==board[0].length)
{
row++;
col=0;
}
//Or Giving a recursive call to avoid changing row manually
// if(col==board[0].length)
// {
// NQueen2DKill(board,tq,qpsf,0,row+1,ans);
// return;
// }
//
//Negative Base Case
if(row==board.length)
return;
if(isItSafeToPlaceQueen(board,row,col))
{
board[row][col]=true;
NQueen2DKill(board,tq,qpsf+1,0,row+1,ans+"{"+row+","+col+"}");
board[row][col]=false;
}
//Not Place
NQueen2DKill(board,tq,qpsf,col+1,row,ans);
}
public static boolean isItSafeToPlaceQueen(boolean[][] board,int row,int col) {
//checking vertically up
int r=row-1;
int c=col;
while(r>=0)
{
if(board[r][c])
return false;
r--;
}
//checking Left
r=row;
c=col-1;
while(c>=0)
{
if(board[r][c])
return false;
c--;
}
//checking diagonally left
r=row-1;
c=col-1;
while(r>=0 && c>=0)
{
if(board[r][c])
return false;
r--;
c--;
}
//checking diagonally right
r=row-1;
c=col+1;
while(r>=0 && c<board[0].length)
{
if(board[r][c])
return false;
r--;
c++;
}
return true;
}
}