【Leetcode】N-Queens

题目链接:https://leetcode.com/problems/n-queens/

题目:

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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

思路:

八皇后问题的扩展,本质全排列问题,解法跟八皇后一样的。

算法:

	int cl[] = null;
	int n = 0;
	List<List<String>> lists = new ArrayList<List<String>>();

	public List<List<String>> solveNQueens(int n) {
		this.n = n;
		this.cl = new int[n];
		search(0);
		return lists;
	}

	void search(int cur) {
		if (cur == n) {
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < cl.length; i++) {
				String s = numToString(cl[i]);
				list.add(s);
			}
			lists.add(list);
			return;
		} else {
			for (int i = 0; i < n; i++) { // 探索每一列
				cl[cur] = i;// 选择i为cur行的列号
				boolean flag = true;
				for (int j = 0; j < cur; j++) {// cur前所有行 若无冲突
					if (cl[j] == i || cur - cl[cur] == j - cl[j] || cur + cl[cur] == j + cl[j])
						flag = false;
				}
				if (flag == true) {
					search(cur + 1);
				}
			}
		}
	}

	public String numToString(int x) {
		String s = "";
		for (int i = 0; i < this.n; i++) {
			s += ".";
		}
		return s.substring(0, x) + "Q" + s.substring(x + 1, n);
	}


你可能感兴趣的:(【Leetcode】N-Queens)