class List { T head; List tail; List(T h, List t) { head = h; tail = t; } static int len( List xs ) { int n = 0; while(xs != null) { n++; xs = xs.tail; } return n; } static List Cons( T h, List t ) { return new List(h,t); } } public class nqueens { static boolean safe( int queen, List xs ) { int diag = 1; while(xs != null) { int q = xs.head; if (queen == q || queen == (q + diag) || queen == (q - diag)) { return false; } diag++; xs = xs.tail; } return true; } static List> appendSafe( int k, List soln, List> solns ) { List> acc = solns; while(k > 0) { if (safe(k,soln)) { acc = List.Cons(List.Cons(k,soln),acc); } k--; } return acc; } static List> extend( int n, List> solns ) { List> acc = null; List> cur = solns; while(cur != null) { acc = appendSafe(n, cur.head, acc); cur = cur.tail; } return acc; } static List> findSolutions( int n ) { int k = 0; List> acc = List.Cons(null,null); while(k < n) { acc = extend(n,acc); k++; } return acc; } static int nqueens(int n) { return List.len(findSolutions(n)); } public static void main(String args[]) { System.out.println( nqueens(Integer.parseInt(args[0])) ); } }