LeetCode: N-Queens

思路:经典的深度搜索题目,当前行尝试将Queen放在每列,如果和前面放好的Queen没有冲突,则开始下一行的搜索,否则,放到下一列,进行同样的冲突检测操作。

code:

class Solution {
public:
    bool isAvailable(vector<string> &board, int r, int c,int n){//与放好的Queen进行冲突检测
        for(int i = 0;i<r;i++)
            if(board[i][c] == 'Q')return false;
        for(int j = 0;j<c;j++)
            if(board[r][j] == 'Q')return false;
        int i = r-1, j = c-1;
        while(i>=0 && j >= 0){
            if(board[i][j] == 'Q')return false;
            i--;
            j--;
        }
        i = r - 1;
        j = c + 1;
        while(i>=0 && j<n){
            if(board[i][j] == 'Q')return false;
            i--;
            j++;            
        }
        return true;
    }
    void NQuees(vector<string> &curRet, int r, int n, vector<vector<string> > &ret){
        if(r >= n){//棋盘中每一行都放了一个Queen,存好结果
            ret.push_back(curRet);
            return;
        }
        string s(n,'.');
        curRet.push_back(s);
        for(int j = 0;j<n;j++){
            vector<string> temp = curRet;
            if(isAvailable(curRet,r,j,n)){
                temp[r][j] = 'Q';//没有冲突,在(r,j)位置放置一个Queen
                NQuees(temp,r+1,n,ret);
            }
            else
                temp[r][j] = '.';//有冲突,不能放置Queen
        }
    }
    vector<vector<string> > solveNQueens(int n) {
        vector<string> board;
        vector<vector<string> > ret;
        NQuees(board,0,n,ret);
        return ret;
    }
};


你可能感兴趣的:(LeetCode: N-Queens)