Leetcode-N-Queens

来源:互联网 发布:淘宝有什么活动 编辑:程序博客网 时间:2024/06/06 00:42

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..”]
]
题意:对于一个nxn的棋盘,里面放n个皇后,彼此之间不再同一行同一列以及同一条对角线上,皇后用Q代替,空格用.代替,求出所有的可能结果。
解题思路:vector < vector < int > > rt表示棋盘,vector< int > v表示n个皇后,v[i]表示i行的皇后所在的列,对i从0到n依次进行尝试,看是否存在解。

   bool iv(vector<int> v,int k)    {        for(int i=1;i<k;++i)        {            if(v[i]==v[k])            {                return false;            }            double xt=k-i;            double yt=v[i]-v[k];            double xy=yt/xt;            if(xy==1||xy==-1)            {                return false;            }        }        return true;    }    void sq(int k,int n,vector<int>& v,vector<vector<string>>& rt)    {            for(int j=1;j<=n;++j)            {                v[k]=j;                if(iv(v,k))                {                        if(k==n)                        {                            vector<string> rv;                            for(int i=1;i<=n;++i)                            {                                string t;                                for(int ii=1;ii<v[i];++ii)                                {                                    t+=".";                                }                                t+="Q";                                for(int ii=v[i]+1;ii<=n;++ii)                                {                                    t+=".";                                }                                rv.push_back(t);                            }                            rt.push_back(rv);                        }                       else                       {                           sq(k+1,n,v,rt);                       }                }                else                {                    v[k]=0;                }            }    }    vector<vector<string>> solveNQueens(int n) {        if(n<1)        {            return vector<vector<string>>();        }        vector<int> v(n+1,0);        vector<vector<string>> ret;        sq(1,n,v,ret);        return ret;    }
0 0
原创粉丝点击