leetcode-51. N-Queens

来源:互联网 发布:windows jenkins 编辑:程序博客网 时间:2024/05/16 04:44

考察点:回溯,递归,矩阵处理;
思路:先将一个矩阵都置为’.’然后开始针对第i行递归,满足row==n条件push_back;然后针对第i行,一次判断第j列是否valid。
C++代码:

class Solution {public:    vector<vector<string>> solveNQueens(int n) {        using namespace std;        vector<vector<string>> ret;        vector<string> nQueens(n,string(n, '.'));        solveNqueens(ret, nQueens, 0, n);        return ret;    }    void solveNqueens(vector<vector<string>> &ret, vector<string> & nQueens, int row, int n) {        if (row == n) {            ret.push_back(nQueens);            return ;        }        for (int col = 0; col <n; col++) {            if (isValid(nQueens, row, col, n)) {                nQueens[row][col] = 'Q';                solveNqueens(ret, nQueens, row+1, n);                nQueens[row][col] = '.';            }        }    }    bool isValid(vector<string>& nQueens, int row, int col, int n) {        for(int i=0; i!=row; i++) {            if (nQueens[i][col] == 'Q')                return false;        }        for (int i=row-1,  j=col-1; i>=0&&j>=0; i--,j--) {            if (nQueens[i][j] == 'Q')                return false;        }        for (int i=row-1,  j=col+1; i>=0&&j<n; i--,j++) {            if (nQueens[i][j] == 'Q')                return false;        }        return true;    }};