51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

由题意得,这是一个八皇后问题,就是有八个皇后,要放置在8 * 8的棋盘上,其中同一行,同一列,同一个对角线不能存在其他的皇后,问有多少种解法。其实这是一题很经典的深搜题,每一行每一行的放置,然后判断是否合法,一直到8个皇后都放完,表示一种解法,而这样的深搜时间复杂度在O(n!),而判断是否合法则需要O(n),那么总的时间复杂度为O(n! * n),代码如下。
Code(LeetCode运行3ms):
class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;
        vector<int> C(n, -1);
        dfs(C, result, 0);
        return result;
    }
    
    void dfs(vector<int>& C, vector<vector<string>>& result, int row) {
        int n = C.size();
        if (row == n) {
            vector<string> aSolution;
            for (int i = 0; i < n; i++) {
                string s(n, '.');
                for (int j = 0; j < n; j++) {
                    if (j == C[i]) {
                        s[j] = 'Q';
                    }
                }
                aSolution.push_back(s);
            }
            result.push_back(aSolution);
            return;
        }
        
        for (int j = 0; j < n; j++) {
            bool valid = isValid(C, row, j);
            if (!valid) {
                continue;
            }
            C[row] = j;
            dfs(C, result, row + 1);
        }
    }
    bool isValid(vector<int>& C, int row, int col) {
        for (int i = 0; i < row; i++) {
            if (C[i] == col) {
                return false;
            }
            if (abs(i - row) == abs(C[i] - col)) {
                return false;
            }
        }
        return true;
    }
};




猜你喜欢

转载自blog.csdn.net/sysu_xiandan/article/details/78924858
今日推荐