n皇后问题java实现

 

 1.要用剪枝,在排列过程中判断当前排列是否合法,如果不合法直接停止,直接回溯

 

 

 1 import java.util.*;
 2 public class Main{
 3     static int n;//输入
 4     static char[][] path=new char[20][20];//路径
 5     //判断路径是否合法
 6     static boolean[] col=new boolean[20];//
 7     static boolean[] left=new boolean[20];//左对角线
 8     static boolean[] right=new boolean[20];//
 9     public static void dfs(int u){
10         if(u==n){//遍历到最后一行了直接输出
11             for(int i=0;i<n;i++){
12                  for(int j=0;j<n;j++){
13                  System.out.print(path[i][j]);
14             }
15             System.out.println();
16             }
17             System.out.println();
18             return;
19         }
20         //遍历
21         for(int i=0;i<n;i++){
22             if(!col[i]&&!left[u+i]&&!right[n-u+i]){
23                 path[u][i]='Q';
24                 col[i]=left[u+i]=right[n-u+i]=true;
25                 dfs(u+1);
26                 col[i]=left[u+i]=right[n-u+i]=false;//恢复现场
27                 path[u][i]='.';
28             }
29         }
30     }
31     public static void main(String[] args){
32         Scanner scan=new Scanner(System.in);
33         n=scan.nextInt();
34         for(int i=0;i<n;i++){
35                  for(int j=0;j<n;j++){
36                 path[i][j]='.';
37             }
38             }
39             dfs(0);
40     
41     }
42 }

 

posted @ 2022-04-08 20:56  经典的错误  阅读(83)  评论(0)    收藏  举报