解法1, 按行回溯:
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static char[][] cs;
static boolean[] dg, udg, col;
public static void main(String[] args) throws Exception{
int n = Integer.valueOf(read.readLine());
cs = 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++){
cs[i][j] = '.';
}
}
bc(0, n);
}
public static void bc(int i, int n){
if(i == n){
for(int k = 0; k < n; k++) System.out.println(cs[k]);
System.out.println();
return;
}
for(int j = 0; j < n; j++){
if(!col[j] && !dg[i + j] && !udg[j - i + n]){
cs[i][j] = 'Q';
col[j] = dg[i + j] = udg[j - i + n] = true;
bc(i + 1, n);
col[j] = dg[i + j] = udg[j - i + n] = false;
cs[i][j] = '.';
}
}
}
}
解法二, 枚举回溯:
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static char[][] cs;
static boolean[] dg, udg, col, row;
public static void main(String[] args) throws Exception{
int n = Integer.valueOf(read.readLine());
cs = new char[n][n];
dg = new boolean[n * 2]; udg = new boolean[n * 2];
col = new boolean[n]; row = new boolean[n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cs[i][j] = '.';
}
}
bc(0, 0, 0, n);
}
public static void bc(int i, int j, int queueNum, int n){
if(j == n) {j = 0; i++;}
if(i == n){
if(queueNum == n){
for(int k = 0; k < n; k++) System.out.println(cs[k]);
System.out.println();
}
return;
}
//不放皇后
bc(i, j + 1, queueNum, n);
//放皇后
if(!row[i] && !col[j] && !udg[j - i + n] && !dg[i + j]){
cs[i][j] = 'Q';
row[i] = col[j] = dg[i + j] = udg[j - i + n] = true;
bc(i, j + 1, queueNum + 1, n);
row[i] = col[j] = dg[i + j] = udg[j - i + n] = false;
cs[i][j] = '.';
}
}
}
你好,想问一下,我用
···
for(int k = 0; k < n; k++) System.out.println(cs[k]);
···
这个输出二维字符数组,只能输出第一行,这是什么原因呢?
只能二重循环输出
我也
是不是因为二维数组的每一行的第n位后面的内容没有被赋值,当打印到后面的内容后,就会结束输出,在编译器中打印出来的也是方框