【Leetcode】N-Queens II

来源:互联网 发布:滴滴打车软件 编辑:程序博客网 时间:2024/06/07 03:36

题目链接: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);}}}}


0 0
原创粉丝点击