博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
八皇后问题——JAVA算法
阅读量:4697 次
发布时间:2019-06-09

本文共 1083 字,大约阅读时间需要 3 分钟。

public 
class 
Queen{
//同栏是否有皇后,1表示有
private 
int
[] column;
 
//右上至左下是否有皇后
private 
int
[] rup;
 
//左上至右下是否有皇后
private 
int
[] lup;
 
//解答
private 
int
[] queen;
 
//解答编号
private 
int 
num;
 
public 
Queen(){
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]=
0
;
 
for
(
int 
i=
1
;i<=(
2
*
8
);i++)
rup[i]=lup[i]=
0
;  
//初始定义全部无皇后
 
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]==
0
)&&(rup[i+j]==
0
)&&(lup[i-j+
8
]==
0
)){
//若无皇后
queen[i]=j;
//设定为占用
column[j]=rup[i+j]=lup[i-j+
8
]=
1
;
backtrack(i+
1
);  
//循环调用
column[j]=rup[i+j]=lup[i-j+
8
]=
0
;
}
}
}
}
 
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){
Queen queen=
new 
Queen();
queen.backtrack(
1
);
}
}

转载于:https://www.cnblogs.com/fangyu1996/p/5893987.html

你可能感兴趣的文章
Android_去掉EditText控件周围橙色高亮区域
查看>>
《构建之法》第一、二、十六章阅读笔记
查看>>
arrow:让Python的日期与时间变的更好
查看>>
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
Java并发编程
查看>>
Git Stash用法
查看>>
sql server 2008学习8 sql server存储和索引结构
查看>>
Jquery radio选中
查看>>
postgressql数据库中limit offset使用
查看>>
测试思想-集成测试 关于接口测试 Part 2
查看>>
php生成器使用总结
查看>>
T-SQL中的indexof函数
查看>>
javascript基础之数组(Array)对象
查看>>
mysql DML DDL DCL
查看>>
RAMPS1.4 3d打印控制板接线与测试1
查看>>
python with语句中的变量有作用域吗?
查看>>
24@Servlet_day03
查看>>
初级ant的学习
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>