# NQueens Puzzle in Java

Place N amount of queens in such a way that none of them can attack each other.

import java.util.*;

public class NQueensRewrite {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount of queens");
int n = input.nextInt();
int[] board = new int[n];
fillBoard(board);
printBoard(board);
}

public static void fillBoard(int[] board) {
int queens = 1;
while (queens < board.length) {
boolean validColumnFound = false;
//Start from previous confirmed column or check all if valid column found in row
for (int column = board[queens] + 1; column < board.length; column++) {
if (isValid(column, queens, board)) {
board[queens] = column;
queens++;
validColumnFound = true;
break;
}
}
//If no other valid column is found, then clear the row and go back to try another column
if (!validColumnFound) {
board[queens] = 0;
queens--;
}
}
}

public static boolean isValid(int column, int row, int[] board) {
//Check if any other row has the specified column
for (int i = 0; i < row; i++) {
if (board[i] == column) {
return false;
}

//Check the differences bewteen the spaces if they are uniform (even)
//If the difference between the column of ith row and column being checked is
//the same as the difference between the current row and row being checked,
//then some previous queen is diagnal to the current spot being checked
if (Math.abs(board[i] - column) == Math.abs(i - row)) {
return false;
}
}
return true;
}

public static void printBoard(int[] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i] == j) {
System.out.print("|Q");
}
else {
System.out.print("| ");
}
}
System.out.println("|");
}
}
}

• I've given answers to N-Queens questions before. A Java one and a C++ one. I don't know how well they would apply to your code, but they might be worth reading. There are surely other good answers on the site, too. – Veedrac May 11 '15 at 14:25
• Follow-up question – 200_success Jun 1 '15 at 22:27

• board is not a board, it is an array of int, with the value of the queen's column. I see the board as being a 2D matrix, you have it as a 1D array.
• queens is not the number of queens, but the number of rows you have currently populated.