码迷,mamicode.com
首页 > 其他好文 > 详细

八皇后

时间:2016-09-21 20:02:21      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:


public class eightqueen {

// 是否有皇后
private int[] column;
// 右上至左下是否有皇后
private int[] rup;
// 左上至右下是否有皇后
private int[] lup;
// 解答
private int[] queen;

// 解答编号
private int num;

public eightqueen() {
column = new int[8+1];
rup = new int[2*8+1];
lup = new int[2*8+1];

for(int i = 1; i <= 8; i++)
column[i] = 1;

for(int i = 1; i <= 2*8; i++)
rup[i] = lup[i] = 1;

queen = new int[8+1];
}

public void backtrack(int i) {
if(i > 8) {
showAnswer();
}
else {
for(int j = 1; j <= 8; j++) {
if(column[j] == 1 &&
rup[i+j] == 1 &&
lup[i-j+8] == 1) {
queen[i] = j;
// 設定為佔用
column[j] = rup[i+j] = lup[i-j+8] = 0;
backtrack(i+1);
column[j] = rup[i+j] = lup[i-j+8] = 1;
}
}
}
}

protected void showAnswer() {
num++;
System.out.println("\n解答 " + num);
for(int y = 1; y <= 8; y++) {
for(int x = 1; x <= 8; x++) {
if(queen[y] == x) {
System.out.print(" Q");
}
else {
System.out.print(" .");
}
}
System.out.println();
}
}

public static void main(String[] args) {
eightqueen queen = new eightqueen();
queen.backtrack(1);
}

}

八皇后

标签:

原文地址:http://www.cnblogs.com/xiaoxiaoguaixiashi/p/5893781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!