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..”]
]
題意:對於一個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;

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章