回溯法的8皇后问题

package backtrack;


public class Queens_demo {
	static int[] result = new int[8];// 全局或成员变量, 下标表示行, 值表示 queen 存储在哪一列
	public static void cal8queens(int row) { // 调用方式:cal8queens(0);
	  if (row == 8) { // 8 个棋子都放置好了,打印结果
	    printQueens(result);
	    return; // 8 行棋子都放好了,已经没法再往下递归了,所以就 return
	  }
	  for (int column = 0; column < 8; ++column) { // 每一行都有 8 中放法
	    if (isOk(row, column)) { // 有些放法不满足要求
	      result[row] = column; // 第 row 行的棋子放到了 column 列
	      cal8queens(row+1); // 考察下一行
	    }
	  }
	}

	private static  boolean isOk(int row, int column) {// 判断 row 行 column 列放置是否合适
	  int leftup = column - 1, rightup = column + 1;
	  for (int i = row-1; i >= 0; --i) { // 逐行往上考察每一行
	    if (result[i] == column) return false; // 第 i 行的 column 列有棋子吗?
	    if (leftup >= 0) { // 考察左上对角线:第 i 行 leftup 列有棋子吗?
	      if (result[i] == leftup) return false;
	    }
	    if (rightup < 8) { // 考察右上对角线:第 i 行 rightup 列有棋子吗?
	      if (result[i] == rightup) return false;
	    }
	    --leftup; ++rightup;
	  }
	  return true;
	}

	private static void printQueens(int[] result) { // 打印出一个二维矩阵
		System.out.println("result:");
	  for (int row = 0; row < 8; ++row) {
	    for (int column = 0; column < 8; ++column) {
	      if (result[row] == column) System.out.print("Q ");
	      else System.out.print("* ");
	    }
	    System.out.println();
	  }
	  System.out.println();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		cal8queens(0);
	}

}

每次递归返回都会返回到上一层。

如果递归不到下一层,就会在当前层继续向后查询。

只有能填完整后也就是
在这里插入图片描述
就会输出一次结果。

然后继续根据状态空间树做DFS知道输出所有结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值