N-Queens II

来源:互联网 发布:php遍历目录 编辑:程序博客网 时间:2024/05/21 22:43

这题和上一题一样就是改一下返回的数值就行了

class Solution {    private:    int ans = 0;public:    bool check(int row, int* used)     {        for (int i = 0; i < row; ++i)         {            int diff = abs(used[i] - used[row]);      // in a col            if (diff == 0 || diff == row - i) {         // int a row or line                return false;            }        }        return true;    }        void solve(int row, int n, int* used)     {        if (row == n) {            ans++;            return;        }                for (int col = 0; col < n; ++col) {     // in 0 row, test n col            used[row] = col;            if (check(row, used)){                solve(row+1, n, used);    // test other rows            }        }    }        int totalNQueens(int n)     {        int *used = new int[n];        solve(0, n, used);                return ans;    }};


0 0
原创粉丝点击