首页 > 代码库 > 【LeetCode】N-Queens

【LeetCode】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.."]
]

     思路

     n 皇后问题,但要输出每个解。只要对每一行进行递归下去就好。


     代码

     C++:

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        /*初始化 vector 变量,第 i 个数代表第 i 行的皇后在哪一列*/
        vector<int> chess(n,-1);
        /*保存结果*/
        vector< vector<string> > ans;
        /*解决问题*/
        solveQueen(0,n,chess.begin(),ans);
        return ans;
    }

    void solveQueen(int r,int n,vector<int>::iterator chess,vector< vector<string> > &ans)
    {
        /*r 等于 n 时每一行都有了皇后*/
        if(r == n)
        {
            /*solution 用于保存一个合法解*/
            vector<string> solution;
            for(int i = 0;i < n;++i)
            {
                solution.push_back(getRowInString(n,*(chess+i)));
            }
            ans.push_back(solution);
            return;
        }

        /*对当前行看哪一列可以放皇后*/
        for(int i = 0;i < n;++i)
        {
            *(chess+r) = i;
            /*检查合法性*/
            if(check(chess,r,n))
            {
                /*向下递归*/
                solveQueen(r+1,n,chess,ans);
            }
        }
    }

    /*检查冲突*/
    bool check(vector<int>::iterator chess,int r,int n)
    {
        /*对之前的每一行*/
        for(int i = 0;i < r;++i)
        {
            /*计算两列的距离*/
            int dis = abs(*(chess+r) - *(chess+i));
            /* dis = 0 则在同一列, dis = r- 1 则构成等腰三角形,即对角线*/
            if(dis == 0 || dis == r - i)
                return false;
        }
        return true;
    }

    /*构造 n 个长度的在 col 为皇后的 string */
    string getRowInString(int n,int col)
    {
        string str(n,'.');
        str.replace(col,1,"Q");
        return str;
    }
};
     Python:

class Solution:
    # @return an integer
    def solveNQueens(self, n):
        self.array = [0 for i in range(0,n)]
        self.ans = []
        self.solve(0,n)
        return self.ans

    def solve(self,r,n):
        if r == n:
            solution = []
            for i in range(0,n):
                row = ['.' for x in range(0,n)]
                row[self.array[i]] = 'Q'
                solution.append(''.join(row))
            self.ans.append(solution)
            del solution
            return
        for i in range(0,n):
            self.array[r] = i
            if self.check(r,n):
                self.solve(r+1,n)

    def check(self,r,n):
        for i in range(0,r):
            dis = abs(self.array[r] - self.array[i])
            if dis == 0 or dis == r - i:
                return False
        return True

【LeetCode】N-Queens