/** * Created by witness on 15-9-26. */ public class Queen { public static void nQueen(int N, int x, int[] trace){ for (int i = 0; i < N; i++){ if (place(trace, x, i)){ trace[x] = i; if (x == N - 1){ for (int j = 0; j < N; j++){ System.out.print(trace[j] + " "); } System.out.println(""); } else { nQueen(N, x + 1, trace); trace[x] = 0; } } } } private static boolean place(int[] trace, int x, int y){ for (int i = 0; i < x; i++){ if (trace[i] == y || (trace[i] - i) == (y - x) || trace[i] + i == x + y){ return false; } } return true; } public static void main(String[] args){ int[] trace = new int[8]; nQueen(8, 0, trace); } }
回溯——N皇后
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.