Skip to content

Instantly share code, notes, and snippets.

@crearo
Created July 26, 2016 21:42
Show Gist options
  • Save crearo/b005a1f841430f60140fd1c343e2c1cf to your computer and use it in GitHub Desktop.
Save crearo/b005a1f841430f60140fd1c343e2c1cf to your computer and use it in GitHub Desktop.
A simple implementation of the 8 queens problem - recursive backtracking.
import java.awt.Point;
public class EightQueens {
/**
* @param args
*/
public static void main(String[] args) {
boolean board[][] = new boolean[8][8];
recBoard(board, 0);
}
public static void recBoard(boolean board[][], int p) {
if (p == 8) {
System.out.println("Found one possible config");
printBoard(board);
return;
} else {
for (int i = 0; i < board.length; i++) {
board[p][i] = true;
if (isBoardValid(board)) {
recBoard(board, p + 1);
}
board[p][i] = false;
}
}
}
public static void printBoard(boolean 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();
}
}
public static boolean isBoardValid(boolean board[][]) {
boolean isValid = true;
Point curr = new Point();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j]) {
curr.x = i;
curr.y = j;
// check left to right
for (int j1 = 0; j1 < board.length; j1++) {
if (board[curr.x][j1] && j1 != curr.y) {
isValid = false;
}
}
// check up to down
for (int i1 = 0; i1 < board.length; i1++) {
if (board[i1][curr.y] && i1 != curr.x) {
isValid = false;
}
}
// check diagonals
int i1 = curr.x;
int j1 = curr.y;
while (i1 > 0 && j1 > 0) {
i1--;
j1--;
if (board[i1][j1])
isValid = false;
}
i1 = curr.x;
j1 = curr.y;
while (i1 < board.length - 1 && j1 < board.length - 1) {
i1++;
j1++;
if (board[i1][j1])
isValid = false;
}
i1 = curr.x;
j1 = curr.y;
while (i1 > 0 && j1 < board.length - 1) {
i1--;
j1++;
if (board[i1][j1])
isValid = false;
}
i1 = curr.x;
j1 = curr.y;
while (i1 < board.length - 1 && j1 > 0) {
i1++;
j1--;
if (board[i1][j1])
isValid = false;
}
}
}
if (!isValid)
break;
}
return isValid;
}
}
@crearo
Copy link
Author

crearo commented Jul 26, 2016

The recBoard is the main recursive function. Just 15 lines does it. Impressive. But the reason the code is this huge is because I couldnt find a better way to validate the board for diagonals in a simpler manner. (Literally ugly code for that part).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment