lintcode-N皇后問(wèn)題

n皇后問(wèn)題是將n個(gè)皇后放置在n*n的棋盤(pán)上,皇后彼此之間不能相互攻擊。

給定一個(gè)整數(shù)n,返回所有不同的n皇后問(wèn)題的解決方案。

每個(gè)解決方案包含一個(gè)明確的n皇后放置布局,其中“Q”和“.”分別表示一個(gè)女王和一個(gè)空位置。

class Solution {
public:
    /**
     * Get all distinct N-Queen solutions
     * @param n: The number of queens
     * @return: All distinct solutions
     * For example, A string '...Q' shows a queen on forth position
     */
     
    vector<vector<string> > ret;
     
    bool check(int * maze, int len) {
        for(int i = 1; i <= len-1; ++i) {
            for(int j = i+1; j <= len; ++j) {
                if(i-j == maze[i]-maze[j] || j-i == maze[i]-maze[j]) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    void process(int * maze, int len) {
        vector<string> tmp;
        for(int i = 1; i <= len; ++i) {
            char * str = new char[len+1];
            int pos = 0;
            //printf("fdsafa");
            for(int j = 1; j <= len; ++j) {
                if(j == maze[i]) {
                    str[pos++] = 'Q';
                } else {
                    str[pos++] = '.';
                }
            }
            str[pos] = '\0'; // 特別注意
            //puts(str);
            string s(str);
            delete [] str;
            tmp.push_back(s);
        }
        ret.push_back(tmp);
    }
    
    void callPermutation(int * maze, int start, int end) {
        
        if(start > end) {
            return;
        }
        
        if(start == end) {
            if(check(maze, end)) {
                
                process(maze, end);
            }
        }
        for(int i = start; i <= end; ++i) {
            swap(maze[start], maze[i]);
            callPermutation(maze, start+1, end);
            swap(maze[start], maze[i]);
        }
    } 
     
    vector<vector<string> > solveNQueens(int n) {
        // write your code here
        
        int * maze = new int[n+1];
        for(int i = 0; i <= n; ++i) {
            maze[i] = i;
        }
        
        callPermutation(maze, 1, n);
        delete [] maze; 
        return ret;
    }
};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容