[leetcode 브러시 시리즈] - N. - Queens.

1524 단어
고전 제목이니 차례차례 검색하면 된다
class Solution {
    const static int MAXN = 100;
    bool col[MAXN], add[MAXN], minus[MAXN];
    int ans[MAXN];
    void dfs(int now, int n, vector<vector<string> >& ret){
        if(now >= n){
            vector<string> vs;
            for(int i = 0; i < n; ++ i){
                string s = "";
                for(int j = 0; j < n; ++ j)
                    if(j == ans[i])
                        s += 'Q';
                    else
                        s += '.';
                vs.push_back(s);
            }
            ret.push_back(vs);
            return ;
        }
        for(int i = 0; i < n; ++ i){
            if(!col[i] && !add[now + i] && !minus[now - i + n]){
                col[i] = true;
                add[now + i] = true;
                minus[now - i + n] = true;
                ans[now] = i;
                dfs(now + 1, n, ret);
                col[i] = false;
                add[now + i] = false;
                minus[now - i + n] = false;
            }
        }
    }
public:
    vector<vector<string> > solveNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        memset(col, 0x00, sizeof(col));
        memset(add, 0x00, sizeof(add));
        memset(minus, 0x00, sizeof(minus));
        vector<vector<string> > ret;
        dfs(0, n, ret);
        return ret;
    }
};

좋은 웹페이지 즐겨찾기