Leetcode - N Queens

Leetcode - 051. N-Queenscode

dfs + backtracing 典型題目ip

須要注意的地方:
1.剪枝放在了下行狀態的循環內部
2.須要判別當前位置能否放置皇后,當前列,兩條對角線都是須要考慮的ci

class Solution {
public:

    bool setable(const vector<string> &cur, const vector<int> & col_used, int row,int col, int n)
    {
        if (col_used[col] == 1)
            return false;
        int i = row - 1;
        int j = col - 1;
        while (i >= 0 && j >= 0)
        {
            if (cur[i][j] == 'Q')
                return false;
            --i;
            --j;
        }
        i = row - 1;
        j = col + 1;
        while (i >= 0 && j < n)
        {
            if (cur[i][j] == 'Q')
                return false;
            --i;
            ++j;
        }
        return true;
    }

    void dfs(vector<vector<string>> &vct, vector<string> &cur, vector<int> & col_used, int row, int n)
    {
        if (row >= n)
        {
            vct.push_back(cur);
            return;
        }
        for (int i = 0; i<n; ++i)
        {
            // try to set queen at a[row][i];
            if (setable(cur, col_used, row, i,n))
            {
                col_used[i] = 1;
                cur[row][i] = 'Q';
                dfs(vct, cur, col_used, row + 1, n);
                cur[row][i] = '.';
                col_used[i] = 0;
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> vct;
        if (n <= 0)
            return vct;
        vector<string> cur(n, string(n, '.'));
        vector<int> col_used(n, 0);
        dfs(vct, cur, col_used, 0, n);
        return vct;
    }
};

Leetcode - 052. N-Queens IIleetcode

惟一不一樣的地方在於:不須要存儲最終的放置方案,只須要統計方案的個數,因此將全部vct替換爲int ans,vct.push_back(cur) 替換爲 ++ans ,最後將ans返回便可(只有返回值表明的含義不一樣,固然如果偷懶的話返回vct.size() 也不是不能夠)get

相關文章
相關標籤/搜索