【Leetcode】N-Queens II

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

题目:

Follow up for N-Queens problem.

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

思路:

跟上题一样。

算法:

	int cl[] = null;
	int n = 0;
	int count = 0;

	public int totalNQueens(int n) {
		this.n = n;
		this.cl = new int[n];
		search(0);
		return count;
	}

	void search(int cur) {
		if (cur == n) {
			count++;
			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);
				}
			}
		}
	}


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