码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】N-Queens

时间:2014-12-11 00:22:24      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:leetcode   n皇后   

     题意

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

bubuko.com,布布扣

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

标签:leetcode   n皇后   

原文地址:http://blog.csdn.net/jcjc918/article/details/41828691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!