题目:
这题的祖宗就是八皇后问题,只需要在初始化的时候给棋盘进行操作就行了;以国王为中心所形成的最小的正方形进行赋值区别就行了(注意边界,例如在四个角的位置。)
注意棋盘的行和列是从1开始。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int a[][], sum = 0, N;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
N = input.nextInt();
int m, n;
m = input.nextInt();
n = input.nextInt();
a = new int[N + 1][N + 1];
for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {
a[i][j] = 1;
}
}
// 初始化棋盘
a[m][n] = 0;
if (m - 1 > 0) {
a[m - 1][n] = 0;
if (n - 1 > 0) {
a[m - 1][n - 1] = 0;
a[m][n - 1] = 0;
}
if (n + 1 < N + 1) {
a[m - 1][n + 1] = 0;
a[m][n + 1] = 0;
}
}
if (m + 1 < N + 1) {
a[m + 1][n] = 0;
if (n - 1 > 0) {
a[m + 1][n - 1] = 0;
a[m][n - 1] = 0;
}
if (n + 1 < N + 1) {
a[m + 1][n + 1] = 0;
a[m][n + 1] = 0;
}
}
// 处理国王所形成的最小的正方形
KingQueen(1);
System.out.println(sum);
}
public static void KingQueen(int i) {
if (i == N + 1) {
sum++;
for (int l = 1; l < N + 1; l++) {
for (int k = 1; k < N + 1; k++)
System.out.print(a[l][k] + ",");
System.out.println();
}
System.out.println();
return;
} //找到一种解法就输出它
int j;
for (j = 1; j < N + 1; j++) {
if (a[i][j] != 0)
if (judge(i, j)) {
a[i][j] = 2;
KingQueen(i + 1);
a[i][j] = 1;
}
} //回溯核心
}
public static boolean judge(int i, int j) {
int r, c;
r = 1;
while (r < i) {
if (a[r][j] == 2)
return false;
r++;
} //判断列
{
r = i - 1;
c = j + 1;
while (r > 0 && c < N + 1) {
if (a[r][c] == 2)
return false;
r--;
c++;
} //判断副对角线
r = i - 1;
c = j - 1;
while (c > 0 && r > 0) {
if (a[r][c] == 2)
return false;
r--;
c--;
} //判断主对角线
}
return true;
}
}