AcWing 843. n-皇后问题 Java
原题链接
中等
作者:
leo_0
,
2020-07-21 15:03:45
,
所有人可见
,
阅读 1256
算法1
Java 代码
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static char[][] grid;
static boolean[] dg, udg, col;
static int n;
public static void main(String[] args) throws Exception{
n = Integer.valueOf(read.readLine());
grid = new char[n][n];
dg = new boolean[n * 2];
udg = new boolean[n * 2];
col = new boolean[n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
grid[i][j] = '.';
}
}
dfs(0);
}
public static void dfs(int row){
if(row == n){
for(int i = 0; i < n; i++) System.out.println(grid[i]);
System.out.println();
return;
}
for(int i = 0; i < n; i++){
if(col[i] || dg[row + i] || udg[i - row + n - 1]) continue;
grid[row][i] = 'Q';
col[i] = dg[row + i] = udg[i - row + n - 1] = true;
dfs(row + 1);
col[i] = dg[row + i] = udg[i - row + n - 1] = false;
grid[row][i] = '.';
}
}
}
import java.util.Scanner;
public class Main {
static int N=20;
static int n;
static char[][] g=new char[N][N];
static boolean[] col=new boolean[N];
static boolean[] dg=new boolean[N];
static boolean[] udg=new boolean[N];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(int i=0;i<n;i) {
for(int j=0;j<n;j) {
g[i][j]=’.’;
}
}
dfs(0);
}
private static void dfs(int u) {
if(u==n) {
for(int i=0;i<n;i) System.out.println(g[i]);
System.out.println();
return;
}
for(int i=0;i<n;i) {
if(!col[i]&&!dg[u+i]&&!udg[n-u+i]) {
g[u][i]=’Q’;
col[i]=dg[u+i]=udg[n-u+i]=true;
dfs(u+1);
col[i]=dg[u+i]=udg[n-u+i]=false;
g[u][i]=’.’;
}
}
}
}
大佬能帮忙看一下哪里有问题不,在编译器里输出结果正确acwing就是不对,过不了