forked from Ishaan28malik/Hacktoberfest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
N Queen problem using java Ishaan28malik#1959
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |