N皇后

/**
 * N皇后<br>
 * https://leetcode-cn.com/problems/n-queens/ <br>
 * 8.53% 递归暴力解..<br>
 * 我的方法太水了<br>
 * 
 * @author wuwang
 *
 */
public class p51 {

	public int totalNQueens(int n) {
		List<List<String>> result = new ArrayList<>();
		List<String> graph = new ArrayList<>(n);
		char[] chs = new char[n];
		for (int i = 0; i < chs.length; ++i)
			chs[i] = '.';
		String line = new String(chs);
		// nxn
		for (int i = 0; i < n; ++i)
			graph.add(line);
		for (int i = 0; i < n; ++i) {
			dfs(0, i, clone(0, i, graph), result, n);
		}
		return result.size();
	}

	public void dfs(int h, int w, List<String> graph, List<List<String>> result, int len) {

		int nh = h + 1;// x的下一行,之前的按照自上而下的顺序已经放置了皇后
		if (nh < len) {
			for (int i = 0; i < len; ++i) {
				if (isvalid(graph, nh, i))
					dfs(nh, i, clone(nh, i, graph), result, len);
			}
		} else {
			result.add(graph);
		}

	}

	public List<String> clone(int h, int w, List<String> oldGraph) {
		List<String> result = new ArrayList<>(oldGraph.size());
		for (int i = 0; i < oldGraph.size(); ++i) {
			if (i == h) {
				char[] chs = oldGraph.get(h).toCharArray();
				chs[w] = 'Q';
				result.add(new String(chs));
			} else {
				result.add(oldGraph.get(i));
			}
		}
		return result;
	}

	public boolean isvalid(List<String> graph, int h, int w) {
		int len = graph.size();
		// 行列
		for (int i = 0; i < len; ++i) {
			if (graph.get(h).charAt(i) == 'Q' || graph.get(i).charAt(w) == 'Q') {
				return false;
			}
		}
		for (int i = h - Math.min(h, w), j = w - Math.min(h, w); i < len && j < len; ++i, ++j) {
			if (graph.get(i).charAt(j) == 'Q') {
				return false;
			}
		}
		for (int i = h, j = w; i < len && j >= 0; ++i, --j) {
			if (graph.get(i).charAt(j) == 'Q') {
				return false;
			}
		}
		for (int i = h, j = w; j < len && i >= 0; --i, ++j) {
			if (graph.get(i).charAt(j) == 'Q') {
				return false;
			}
		}

		return true;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值