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

LeetCode N-Queens

时间:2014-12-03 21:17:08      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:leetcode   八皇后   matrix   

又是一个八皇后问题:

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.."]
]
bubuko.com,布布扣

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        this->N=n;
        memset(matrix,0,sizeof(matrix));
        dfs(0);
        return d;
    }
    int check(int x,int y)
        {
            for(int j=0;j<y;++j)
                if(matrix[x][j]==1)return 0;
            for(int i=0;i<N;++i)
                for(int j=0;j<y;++j)
                {
                    if(abs(i-x)==abs(j-y)&&matrix[i][j]==1)return 0;
                }
            return 1;
        }
    void dfs(int j)
        {
            if(j==N)
            {
                //存储
                vector<string>mt;
                for(int i=0;i<N;++i){
                    string td;
                    for(int j=0;j<N;++j)
                    {
                        if(matrix[i][j]==0)td+='.';
                        if(matrix[i][j]==1)td+='Q';
                    }
                    mt.push_back(td);
                }
                d.push_back(mt);
                return ;
            }
            for(int i=0;i<N;++i)
            {
                if(matrix[i][j]==0&&check(i,j))
                {
                    matrix[i][j]=1;
                    dfs(j+1);
                    matrix[i][j]=0;
                }
            }
        }
private :
    int N;
    vector<vector<string> > d;
    int matrix[100][100];
};


LeetCode N-Queens

标签:leetcode   八皇后   matrix   

原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41703259

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