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

leetcode-51-N-Queens

时间:2015-06-27 09:50:33      阅读:120      评论:0      收藏:0      [点我收藏+]

标签: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.."]
]



将每一种可能都输出

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        dfs_2(0,n);
        return b;
    }
    int num;
    int v[3][100];
    vector<string>a;
    int c[100];
    vector<vector<string>>b;
    int dfs_2(int cur,int n) // 填充第cur行
    {
        if(cur==n){
           a.clear();
           for(int i=0;i<n;i++){ // vector<string>a;  a 为每一种方案 
              string s(n,'.');  //首先赋初值
              s[c[i]]='Q';      // 将每一行的queen的位置用Q表示
              a.push_back(s);    // 加入到a中
           }
           b.push_back(a); // 将每一种可能加入b中
        }
        else{
           for(int i=0;i<n;i++){// 列
               if(!v[0][i]&&!v[1][cur-i+n]&&!v[2][cur+i]){
                   v[0][i]=v[1][cur-i+n]=v[2][cur+i]=1;
                   c[cur]=i;
                   dfs_2(cur+1,n);
                   v[0][i]=v[1][cur-i+n]=v[2][cur+i]=0;
               }
           }
       }
    }
    
};




 

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode-51-N-Queens

标签:leetcode

原文地址:http://blog.csdn.net/u014705854/article/details/46656105

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