import java.util.*;
public class Main {
public static int count=0;
private static Scanner sc;
public static void main(String[] args) {
// TODO Auto-generated method stub
sc=new Scanner(System.in);
int n=sc.nextInt();
queenCombinationBoxRespect2DKill(new boolean[n][n],0,0,0,n);
System.out.println(count);
}
public static void queenCombinationBoxRespect2DKill(boolean[][] board,int row,int col,int qpsf,int tq) {
//POSITIVE BASE CASE
if(qpsf==tq) {
count++;
return;
}
//MANUALLLY CHANGE VARIABLES
if(col==board[0].length) {
row++;
col=0;
//return; NO RETURN BECAUSE WE HAVE TO EXECUTE THIS ROW FURTHER.
}
//NEGATIVE BASE CASE
if(row==board.length) {
return;
}
if(isItSafeToPlace(board,col,row)) {
board[row][col]=true;//PLACE QUEEN
queenCombinationBoxRespect2DKill(board,row+1,0,qpsf+1,tq);
board[row][col]=false;//UNDO
}
queenCombinationBoxRespect2DKill(board,row,col+1,qpsf,tq);
}
public static boolean isItSafeToPlace(boolean[][]board,int col,int row) {
int r=row-1;//MANDATORY TO KEEP TRACK OF POSITION
int c=col;
//UPWARD
while(r>=0) {
if(board[r][col]) {
return false;
}
r–;
}
//HORIZONTAL
r=row-1;
c=col;
while(c>=0) {
if(board[row][c]) {
return false;
}
c–;
}
//DIAGONAL LEFT
r=row-1;
c=col-1;
while(r>=0&&c>=0) {
if(board[r][c]) {
return false;
}
r–;
c–;
}
//DIAGONAL RIGHT
r=row-1;
c=col+1;
while(r>=0&&c<board[0].length) {
if(board[r][c]) {
return false;
}
c++;
r–;
}
return true;// IF CODE REACHES HERE IT IS SAFE
}
}
Test Case 2 TLE. How do I fix this?
In isItSafeToPlace finction
// HORIZONTAL
r = row;
c = col-1;
while (c >= 0) {
if (board[row][c]) {
return false;
}
c–;
}
optimize approach used for N queen problem
1.Start in the leftmost column .
2. If all queens are placed return true .
3. Try all rows in the current column. Do following for every tried row.
If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution.
If placing the queen in [row, column] leads to a solution then return true.
If placing queen doesn’t lead to a solution then umark this [row, column] and go to try other rows.
If all rows have been tried and nothing worked, return false to trigger backtracking.
you can see this