基础练习 2n皇后问题
接下来n行,每行n个0或1的整数,如果一个整数为1,表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
0
code: ac
//利用回溯法,此问题是在n皇后的变形得到的,应该先搞清n皇后在写此问题
import java.util.*;
import java.io.*;
public class Main {
static int n, count = 0;
static int Map[][];
static boolean[][] vis;
static boolean[][] a;
static boolean[][] b;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
Map = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
Map[i][j] = in.nextInt();
vis = new boolean[n + 1][n + 1];
a = new boolean[3][n * 2];
b = new boolean[3][n * 2];
dfs(0);
System.out.println(count);
}
private static void dfs(int cur) {
if (cur == n) {
count++;
return;
}
for (int i = 0; i < n; i++) {
if (!vis[cur][i] && Map[cur][i] != 0) {
if (!a[0][i] && !a[1][cur + i] && !a[2][cur - i + n]) {
vis[cur][i] = true;
a[0][i] = a[1][cur + i] = a[2][cur - i + n] = true;
for (int j = 0; j < n; j++) {
if (!vis[cur][j] && Map[cur][j] != 0) {
if (!b[0][j] && !b[1][cur + j]
&& !b[2][cur - j + n]) {
vis[cur][j] = true;
b[0][j] = b[1][cur + j] = b[2][cur - j + n] = true;
dfs(cur + 1);
vis[cur][j] = false;
b[0][j] = b[1][cur + j] = b[2][cur - j + n] = false;
}
}
}
//dfs(cur + 1);
vis[cur][i] = false;
a[0][i] = a[1][cur + i] = a[2][cur - i + n] = false;
}
}
}
}
}