Skip to content

Instantly share code, notes, and snippets.

@bittib
Last active December 9, 2016 07:08
Show Gist options
  • Save bittib/5449327 to your computer and use it in GitHub Desktop.
Save bittib/5449327 to your computer and use it in GitHub Desktop.
N Queen Problem. Print all solutions for N queen based on either row first order or column first. http://poj.grids.cn/practice/2698/
import java.io.*;
public class Main{
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static int N = 8;
static int cnt = 0;
public static void main(String[] args){
int[] array = new int[N];
cnt = 0;
dfs(array, 0);
pw.close();
}
static void dfs(int[] array, int idx){
if (idx == N){
output(array, false);
return;
}
for (int i=0; i<N; i++){
if (isSafe(array, i, idx)){
array[idx] = i;
dfs(array, idx+1);
}
}
}
// check if columnId is a safe position for row[rowId]
static boolean isSafe(int[] array, int columnId, int rowId){
for (int i=0; i<rowId; i++){
if (array[i] == columnId || Math.abs(i - rowId) == Math.abs(array[i] - columnId))
return false;
}
return true;
}
static void output(int[] array, boolean rowFirst){
cnt++;
pw.println("No. " + cnt);
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
boolean expr = j == array[i];
if (!rowFirst)
expr = i == array[j];
if (expr)
pw.print("1 ");
else
pw.print("0 ");
}
pw.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment