Leetcode解题笔记之(51)-- N-Queens [Hard]

解题思路

N皇后问题就是是NP完全类问题的一个典型实例,它没有多项式时间算法解。
在设计算法求解的时候,我们应该尽量考虑减少搜索次数和判断次数,尽量减少循环和递归的次数,从而降低求解耗时。
注意:将棋盘上不能放的点去除。因为是按照每行每行去放皇后,所以只需要判断西北方和东北方以及上方有无皇后即可,下方由于row 值更大,不存在皇后,无须判断。递归执行后记得将点复原。

代码

    void solveNQueens(vector<vector<string>>& res, vector<string>& nQueens, int row, int& n) {
        if (row == n) {
            res.push_back(nQueens);
            return;
        }

        for (int col = 0; col < n; col++) {
            if (isValid(nQueens, row, col, n)) {
                nQueens[row][col] = 'Q';
                solveNQueens(res, 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;
    }
    
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<string> nQueens(n, string(n, '.'));
        solveNQueens(res, nQueens, 0, n);
        return res;
    }

猜你喜欢

转载自blog.csdn.net/cjinchan/article/details/84714608