DFS回溯法解决N皇后问题
思路:因为每一行有n个位置可放置皇后(不考虑合不合理),所以此问题可以抽象出一个n+1层(含根节点)的n叉树。然后对该树进行剪枝(DFS回溯)即可求出可行解。
手撸代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
   | import java.util.Arrays; import java.util.Scanner;
  public class NQueens { 	public static int count=0; 	 	public boolean check(int row,int col,int n,int[] queue) { 		for (int i = 0; i < row; i++) { 			 			if(Math.abs(i-row)==Math.abs(queue[i]-col))return false; 		} 		return true; 	} 	public void calNQueens(int row,int n,int[] queue,boolean[] hasuse) { 		if(row==n){ 			count++; 			return; 		} 		 		for(int col=0;col<n;col++){ 			if (!hasuse[col]&&check(row, col, n, queue)) { 				hasuse[col]=true; 				queue[row]=col; 				calNQueens(row+1, n, queue, hasuse); 				 				hasuse[col]=false; 				queue[row]=-1; 			} 		} 	}
  	public static void main(String[] args) { 		 		Scanner scanner=new Scanner(System.in); 		int n=scanner.nextInt(); 		int[] queue=new int[n]; 		Arrays.fill(queue, -1); 		boolean[] hasuse=new boolean[n]; 		new NQueens().calNQueens(0, n, queue, hasuse); 		System.out.println(count); 	} }
   | 
 
附:leetcode解法