Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 22, 2013 23:00
Show Gist options
  • Save charlespunk/5017271 to your computer and use it in GitHub Desktop.
Save charlespunk/5017271 to your computer and use it in GitHub Desktop.
Write an alogrithm to print all ways of arranging eight queens on an 8*8 chess board so that none of them share the same row, colum or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.
public static ArrayList<int[]> Queues(){
ArrayList<int[]> ways = new ArrayList<>();
int[] colums = new int[COLUMSIZE];
queues(0, colums, ways);
return ways;
}
public static void queues(int colum, int[] colums, ArrayList<int[]> ways){
if(colum == COLUMSIZE) ways.add(colums.clone);
for(int i = 0; i < ROWSIZE; i++){
if(check(colum, i, colums){
colums[colum] = i;
queues(colum + 1, colums, ways);
}
}
}
public static boolean check(int colum, int value, int[] colums){
for(int i = 0; i < colum; i++){
if(colums[i] == value) return false;
if(Math.abs(colums[i] - value) == colum - i) return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment