利用栈解决八皇后问题
//定义棋盘位置
class Point{
int x = -1;
int y = -1;
public Point() {}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class HuangHou {
private int stackSize = 8; //定义栈的深度
public void placeQueen(Stack<Point> pointStack, int row2,int col2){
for (int row = row2; row < stackSize; row++) {
for (int col = col2; col < stackSize; col++) {
Point point = new Point(row, col);
pointStack.push(point);
if (judge(pointStack)) {
//递归开始判断第二行
if (row < stackSize - 1) {
placeQueen(pointStack, row+1, 0);
}else {
//打印出来
if (pointStack.getTop() == stackSize - 1) {
System.out.println("*********有结果***********");
}
}else {
pointStack.pop();
}
}
}
}
//判断位置是否合法
public boolean judge(Stack<Point> pointStack){
Object[] data = pointStack.getData();
Point topPoint = (Point) pointStack.peek();
for (int i = 0; i < pointStack.getTop(); i++) {
Point point = (Point) data[i];
int x = point.x;
int y = point.y;
//是否在同一行
if (x == topPoint.x) {
return false;
}
//是否在同一列
if (y == topPoint.y) {
return false;
}
//是否在对角线上
if (Math.abs(topPoint.x - x) == Math.abs(topPoint.y - y)) {
return false;
}
}
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论