【Leetcode】N-Queens II (Backtracking)

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.


N皇后问题是经典的NP问题,也是经典的回朔问题,思想就是放棋子,然后检查放的合不合理,如果不合理就撤回,然后继续放其他格子,直到合理位置。

至于如何检查,主要就是检查行列和对角线

	public static boolean check(int row, int[] column) {
		for (int i = 0; i < row; i++) {
			if (column[i] == column[row]
					|| Math.abs(column[row] - column[i]) == (row - i))
				return false;
		}
		return true;
	}

column[i]=j代表的意思是这个棋盘的第i行第j列被占用了

column[i]==column[row]代表的意思是第i行和第row行占用了同一列

column[row]-column[i]==row-i代表第i行和第row行在主对角线上

column[row]-column[i]==i-row代表第i行和第row行在副对角线上


然后每次就放,检查,回朔就可以了

完整代码如下

	public static int totalNQueens(int n) {
		if (n <= 0)
			return 0;
		int[] column = new int[n];
		ArrayList<Integer> result = new ArrayList<Integer>();
		result.add(0);
		helper(n, 0, column, result);
		return result.get(0);
	}

	public static void helper(int n, int row, int[] column,
			ArrayList<Integer> result) {
		if (row == n) {
			result.set(0, result.get(0) + 1);
			return;
		}
		for (int i = 0; i < n; i++) {
			column[row] = i;
			if (check(row, column)) {
				helper(n, row + 1, column, result);
			}
		}
	}

	public static boolean check(int row, int[] column) {
		for (int i = 0; i < row; i++) {
			if (column[i] == column[row]
					|| Math.abs(column[row] - column[i]) == (row - i))
				return false;
		}
		return true;
	}

这里之所以不用恢复现场的原因是因为只用了一位数组记录没一行所被占的列,如果被占,那就跳过,就相当于是没有放,所以不存在被占用的情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值