Skip to content

Commit

Permalink
Create NQueen_Problem.java
Browse files Browse the repository at this point in the history
N Queen problem using java Ishaan28malik#1959
  • Loading branch information
Manik1811 authored Oct 16, 2023
1 parent 6e9e35e commit e6b7eb8
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Java_Programs-master/NQueen_Problem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//N Queen problem using java #1959
class NQueen_Problem{
public static boolean isSafe(char chessBoard[][],int row,int col){
//vertical up
for(int i=row-1;i>=0;i--){
if(chessBoard[i][col]=='Q'){
return false;
}
}
//left diag up
for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
if(chessBoard[i][j]=='Q'){
return false;
}
}
//right diag up
for(int i=row-1,j=col+1;i>=0 && j<chessBoard.length;i--,j++){
if(chessBoard[i][j]=='Q'){
return false;
}
}
return true;
}
public static void nQueen(char chessBoard[][], int row){
//Base case
if(row==chessBoard.length){
printBoard(chessBoard);
return;
}
//cloumn loop
for(int j=0;j<chessBoard.length;j++){
if (isSafe(chessBoard,row,j)){
chessBoard[row][j]='Q';
nQueen(chessBoard, row+1); //function call
chessBoard[row][j]='x'; //backtrack
}
}
}
public static void printBoard(char chessBoard[][]){
System.out.println("----Chess-Board----");
for(int i=0;i<chessBoard.length;i++){
for(int j=0;j<chessBoard.length;j++){
System.out.print(chessBoard[i][j]+" ");
}
System.out.println();
}
}

0 comments on commit e6b7eb8

Please sign in to comment.