Skip to content

Instantly share code, notes, and snippets.

@liyamahendra
Created August 27, 2015 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyamahendra/ba139f31b81afe69ed05 to your computer and use it in GitHub Desktop.
Save liyamahendra/ba139f31b81afe69ed05 to your computer and use it in GitHub Desktop.
public class QueensProblem {
private static int boardSize = 8; // default board size is 8x8
private static int[] board = new int[boardSize];
private static StringBuilder output;
public static void main(String[] args) {
if(args != null && args.length > 0) {
try {
boardSize = Integer.parseInt(args[0]);
board = new int[boardSize];
} catch(NumberFormatException ex) {
System.out.println("Invalide board size provided.");
}
}
if(boardSize < 4 || boardSize > 25) {
System.out.println("Board size is out the permissible value of 4 and 25 (both inclusive)");
System.exit(1);
}
output = new StringBuilder();
placeAllQueens(board, 0);
}
private static void placeAllQueens(int board[], int row){
if(row == board.length) {
prepareBoard(board);
output.deleteCharAt(output.length() - 1);
System.out.println("Queens on: " + output.toString());
System.exit(1);
} else {
for (int col = 0; col < board.length; col++) {
board[row] = col;
if(isPlacingSafe(board, row)){
placeAllQueens(board, row+1);
}
}
}
}
private static boolean isPlacingSafe(int[] board, int currentRow) {
for (int previousRows = 0; previousRows < currentRow; previousRows++) {
//Same Column Checking
if(board[currentRow] == board[previousRows]) {
return false;
}
//Minor Diagonal Checking
if( (board[currentRow] - board[previousRows]) == currentRow - previousRows) {
return false;
}
//Major Diagonal Checking
if( (board[previousRows] - board[currentRow]) == currentRow - previousRows) {
return false;
}
//Major and Minor Diagonal Checking
if (Math.abs(board[currentRow] - board[previousRows]) == Math.abs(currentRow - previousRows)) {
return false;
}
}
return true;
}
private static void prepareBoard(int[] board){
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board.length; col++) {
if(board[row] == col){
output.append("(" + (row + 1) + "," + (col + 1) + "),");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment