Skip to content

Instantly share code, notes, and snippets.

@myrtleTree33
Last active April 22, 2020 15:22
Show Gist options
  • Save myrtleTree33/2a0d263af7b5356bda28e2229dc23f92 to your computer and use it in GitHub Desktop.
Save myrtleTree33/2a0d263af7b5356bda28e2229dc23f92 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
public class NQueens {
private static boolean nQueens(int[][] board, int col) {
if (col >= board.length) {
return true;
}
for (int row = 0; row < board.length; row++) {
if (isSafe(board, row, col)) {
board[row][col] = 1;
// If successfully put the next queen
if (nQueens(board, col + 1)) {
return true;
}
// Backtrack
board[row][col] = 0;
}
}
return false;
}
private static boolean isSafe(int[][] board, int row, int col) {
for (int j = 0; j < col; j++) {
if (board[row][j] == 1) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (int i = row, j = col; i < board.length && j >= 0; i++, j--) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
public static void printSoln(int[][] board) {
for (int i = 0; i < board.length; i++) {
System.out.println(Arrays.toString(board[i]));
}
}
public static void main(String[] args) {
int[][] board = new int[8][8];
if (!nQueens(board, 0)) {
System.out.println("No such solution can be found.");
return;
}
printSoln(board);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment