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

Leetcode题解(7)L51/N-Queens

时间:2015-06-09 17:32:04      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   backtrack   n-queens   

L51: 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..”]
]

解题思路:典型的回溯法,可用递归或非递归解决

class Solution {
public:
    bool isAttack(vector<int> queens, int k)
    {
        if(k == 0)
            return false;
        for (int i=0; i<k; i++)
        {
            if(queens[k] == queens[i] || abs(k-i) == abs(queens[k]-queens[i]))
                return true;
        }
        return false;
    }

    void showQueens(vector<int> queens, vector<vector<string> >& result){
        int n = queens.size();
        vector<string> vec(n, string(n,‘.‘));

        for(int i = 0; i < n; i++)
            vec[i][queens[i]] = ‘Q‘;

        result.push_back(vec);  
    }

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > result;
        vector<int> queens(n,0);

        if(n == 1)
        {
            vector<string> vec(1, string(‘Q‘));
            result.push_back(vec);
            return result;
        }

        int i = 0;

        while(1)
        {
            while(i < n)
            {
                while(queens[i] == n)
                {
                    queens[i--] = 0;    
                    if(i == -1)
                        return result;
                    queens[i]++;
                }                                   
                if(isAttack(queens,i))      
                    queens[i]++;
                else
                    i++;
            }
            showQueens(queens,result);

            queens[n-1] = 0;
            i = n-2;
            queens[i]++;
        }
    }
};

Leetcode题解(7)L51/N-Queens

标签:leetcode   backtrack   n-queens   

原文地址:http://blog.csdn.net/kzq_qmi/article/details/46426309

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