package com.wentora.exercise; /** * 回溯法求解n皇后问题 * @author wentora */ import java.util.Scanner; public class Queens { int[] res; int size; Queens(int size) { this.size = size; res = new int[size + 1]; } boolean place(int k) { for(int i = 0; i < k; i++) { if(res[i] == res[k] || Math.abs(i - k) == Math.abs(res[i] - res[k])) return false; } return true; } int sum = 0; void backtrack(int start) { if(start == size) { sum++; System.out.print("the " + sum + " combination : "); for(int i = 0; i < size; i++) System.out.print(res[i] + 1 + " "); System.out.println(); return; } for(int i = 0; i < size; i++) { res[start] = i; if(place(start)) { backtrack(start + 1); } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("please input size : "); int size; Scanner in = new Scanner(System.in); size = in.nextInt(); Queens queen = new Queens(size); queen.backtrack(0); System.out.println("there are " + queen.sum + " combinations."); } }