//if n == N, print the result if (n == N) { for (inti=0; i < result.length; i++) { System.out.print(result[i] + ","); } System.out.println(); resultNum++; } else { for (inti=0; i < N; i++) { // test every location possible result[n] = i; //if line n is allowed, locate the next line if (isAllowed(n)) { calculation(n + 1); } } } }
/** * judge current line is allowed or not. */ privatebooleanisAllowed(int i) { // i is not allowed while it in same line or diagonal with the pre line for (intj=0; j < i; j++) { if (result[i] == result[j] || Math.abs(i - j) == Math.abs(result[i] - result[j])) { returnfalse; } } returntrue; }
//main method, include some test cases publicstaticvoidmain(String[] args) { NQueenqueen=newNQueen();