LeetCode 52 N-Queens II

来源:互联网 发布:程序员对笔记本尺寸 编辑:程序博客网 时间:2024/05/17 23:57

题意:

n皇后问题,与 http://blog.csdn.net/houserabbit/article/details/72758088 不同,本题指数出解的个数,不要求方案。


思路:

可以用一下比LeetCode 51更优化的搜索方法,每放置一个皇后,我们记录它可以攻击哪一列、以及通过斜线攻击到的第一行的某2个位置。这样在放置皇后的时候,是否能放置到某个位置就可以O(1)判断了。


代码:

class Solution {public:    int totalNQueens(int n) {        int *column = new int[n];        int *left = new int[n * 2];        int *right = new int[n * 2];        memset(column, 0, sizeof(column));        memset(left, 0, sizeof(left));        memset(right, 0, sizeof(right));        int ans = 0;        dfs(0, n, column, left, right, &ans);        return ans;    }private:    void dfs(int row, int total, int *column, int *left, int *right, int *ans) {        if (row == total) {            ++(*ans);            return;        }        for (int i = 0; i < total; ++i) {            int l = i - row + total - 1, r = i + row;            if (!column[i] && !left[l] && !right[r]) {                column[i] = left[l] = right[r] = 1;                dfs(row + 1, total, column, left, right, ans);                column[i] = left[l] = right[r] = 0;            }        }    }};