LeetCode N-Queens

Description:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.


Solution:

这道题目太经典了,第一轮没做的原因是担心n太大,TLE,但是后来一想,似乎用二进制已经是最快速的了。

具体的做法可以参考Matrix67原始解说。

基本思路就是用二进制来表示三条线(因为N皇后问题,在第k曾就是有三个方向的限制),一条是最简单的竖直方向限制(这个就和车一样),然后是左右两个斜对角。

状态表示完之后,就判断在这三个方向上是否冲突,如果不冲突,则更新状态,递归到下一层。


注:这里debug了好久的一个地方,如果要把一个char数组转换成String,不能用char[].toString(),而应该用new String(char[])


<span style="font-size:18px;">import java.util.*;

public class Solution {
	List<List<String>> list;
	int n;
	char[] char_list;

	public List<List<String>> solveNQueens(int n) {
		list = new ArrayList<List<String>>();
		this.n = n;
		int[] choose = new int[n];
		char_list = new char[n];
		Arrays.fill(char_list, '.');

		dfs(0l, 0l, 0l, 0, choose);

		return list;
	}

	int count = 0;

	public void dfs(long vertical, long left, long right, int step, int[] choose) {
		if (step == n) {
			count++;
			List<String> chessboard = new ArrayList<String>();
			for (int i = 0; i < n; i++) {
				char_list[choose[i]] = 'Q';
				String str = new String(char_list);
				char_list[choose[i]] = '.';
				chessboard.add(str);
			}
			list.add(chessboard);
		} else {
			for (int i = 0; i < n; i++) {
				long line = 1l << i;
				if ((vertical & line) > 0 || (left << 1 & line) > 0
						|| (right >> 1 & line) > 0)
					continue;
				choose[step] = i;
				dfs((vertical | line), (left << 1 | line), (right >> 1 | line),
						step + 1, choose);
			}
		}
	}
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值