public class Main3
{
public static void nQueens( char[][] board,int row){
if(row== board.length) {
printBoard(board);
return;
}
for (int j = 0; j < board.length; j++) {
if(isSafe(board,row,j)){
board[row][j]='Q';
nQueens(board,row+1);
board[row][j]='X';
}
}
}
public static void printBoard(char[][] board){
System.out.println("---------chess board---------");
for (char[] chars : board) {
for (int j = 0; j < board.length; j++) {
System.out.print(chars[j] + " ");
}
System.out.println();
}
}
public static boolean isSafe(char[][] board,int row,int col){
for(int i=row-1;i>=0;i--){
if(board[i][col]=='Q') return false;
}
for(int i=row-1,j=col+1;i>=0&&j< board.length;i--,j++){
if(board[i][j]=='Q') return false;
}
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
if(board[i][j]=='Q') return false;
}
return true;
}
public static void main(String[] args){
int n=8;
char[][] board=new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j]='X';
}
}
nQueens(board,0);
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter