nqueens problem:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> ans;
        vector<int> store(n,-1);
        dfs(ans,store,0,n);
        return ans;
    }
    void dfs(vector<vector<string>>& res,vector<int>& store,int curRow,int n)
    {
        if(curRow==n) 
        {
            //store and return
            vector<string> tmp;
            for(int i=0;i<store.size();++i)
            {
                //trick string可以直接初始化(n,'.')
                string str(n,'.');
                str[store[i]]='Q';
                tmp.push_back(str);
            }
            res.push_back(tmp);
            return;
        }
        //bug:only one loop dfs只递归当前行的排列即可
        for(int i=0;i<n;++i)
        {
                if(isValid(curRow,i,store))
                {
                    store[curRow]=i;
                    //bug curRow要加1,每次要统计下一行
                    dfs(res,store,curRow+1,n);
                    store[curRow]=-1;
                }
        }
    }
    bool isValid(int m,int n,vector<int>& store)
    {
        //bug: i<m 在该行前才有棋子,该行后没有遍历的必要
        for(int i=0;i<m;++i)
        {
            if(n==store[i]||abs(i-m)==abs(store[i]-n)) return false;
        }
        return true;
    }
};

 

posted on 2020-10-12 22:19  黑暗尽头的超音速炬火  阅读(101)  评论(0)    收藏  举报