八皇后问题
来源:互联网 发布:人工智能雄帝科技 编辑:程序博客网 时间:2024/06/06 18:19
public class Queen {
static int N =8;
static int column[] = new int[N + 1]; // 同栏是否有皇后,1表示有
static int rup[] = new int[2 * N + 1]; // 右上至左下是否有皇后
static int lup[] = new int[2 * N + 1]; // 左上至右下是否有皇后
static int queen[] = new int[N + 1];
static int num = 0; // 解答编号
public static void main(String[] args) {
int i;
num = 0;
for (i = 1; i <= N; i++)
column[i] = 1;
for (i = 1; i <= 2 * N; i++)
rup[i] = lup[i] = 1;
backtrack(1);
}
static void showAnswer() {
int x, y;
System.out.println("解答 " + ++num);
for (y = 1; y <= N; y++) {
for (x = 1; x <= N; x++) {
if (queen[y] == x) {
System.out.print(" Q");
} else {
System.out.print(" .");
}
}
System.out.println("\n");
}
}
static void backtrack(int i) {
int j;
if (i > N) {
showAnswer();
} else {
for (j = 1; j <= N; j++) {
if (column[j] == 1 && rup[i + j] == 1 && lup[i - j + N] == 1) {
queen[i] = j;
// 设定为占用
column[j] = rup[i + j] = lup[i - j + N] = 0;
backtrack(i + 1);
column[j] = rup[i + j] = lup[i - j + N] = 1;
}
}
}
}
}
static int N =8;
static int column[] = new int[N + 1]; // 同栏是否有皇后,1表示有
static int rup[] = new int[2 * N + 1]; // 右上至左下是否有皇后
static int lup[] = new int[2 * N + 1]; // 左上至右下是否有皇后
static int queen[] = new int[N + 1];
static int num = 0; // 解答编号
public static void main(String[] args) {
int i;
num = 0;
for (i = 1; i <= N; i++)
column[i] = 1;
for (i = 1; i <= 2 * N; i++)
rup[i] = lup[i] = 1;
backtrack(1);
}
static void showAnswer() {
int x, y;
System.out.println("解答 " + ++num);
for (y = 1; y <= N; y++) {
for (x = 1; x <= N; x++) {
if (queen[y] == x) {
System.out.print(" Q");
} else {
System.out.print(" .");
}
}
System.out.println("\n");
}
}
static void backtrack(int i) {
int j;
if (i > N) {
showAnswer();
} else {
for (j = 1; j <= N; j++) {
if (column[j] == 1 && rup[i + j] == 1 && lup[i - j + N] == 1) {
queen[i] = j;
// 设定为占用
column[j] = rup[i + j] = lup[i - j + N] = 0;
backtrack(i + 1);
column[j] = rup[i + j] = lup[i - j + N] = 1;
}
}
}
}
}
0 0
- 八皇后 n皇后 问题
- 八皇后N皇后问题
- 八皇后问题
- 八皇后问题
- 八皇后问题
- 八皇后问题(2)
- 八皇后问题(3)
- 八皇后问题
- 八皇后问题程序
- 浅谈八皇后问题
- 八皇后问题
- 八皇后问题
- 八皇后问题
- 八皇后问题
- 八皇后问题求解
- 八皇后问题
- 八皇后问题
- 八皇后问题
- Android常见知识点
- 创建xmlhttprequest对象
- poj 1469 COURSES 【二分匹配】
- C面试题(判断大端小端)
- Mysql不能插入中文(彻底解决)
- 八皇后问题
- 分数化小数
- velocity 的js里面循环对象使用#foreach
- 实例讲解虚拟机3种网络模式(桥接、nat、Host-only)
- 一个字符引发的思考
- 自建企业邮箱如何选择服务器
- MSSQL语句的性能调试(一)使用OR还是Exists
- 浅谈C++中指针和引用的区别
- 灰度变换——反转,对数变换,伽马变换,灰度拉伸,灰度切割,位图切割