"Leetcode" N-queens

Source: Internet
Author: User

Test instructions

The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.

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 Indi Cate a queen and an empty space respectively.

For example,
There exist-distinct solutions to the 4-queens puzzle:

[ [". Q.. ",  //solution 1  " ... Q ",  " Q ... ",".  . Q. "], ["]. Q. ",  //Solution 2  " Q ... ",  " ... Q ",  ". Q.. "]

Ideas

N Queen problem, but to output each solution. Just give each line a recursive go.


Code

C++:

Class Solution {public:vector<vector<string> > Solvenqueens (int n) {/* Initialize vector variable, number of I represents line I        The Queen in which column */vector<int> chess (n,-1);        /* Save Results */vector< vector<string> > ans;        /* Solve the problem */Solvequeen (0,n,chess.begin (), ans);    return ans;        } void Solvequeen (int r,int n,vector<int>::iterator chess,vector< vector<string> > &ans) { /*r equals n When each row has a queen * * if (r = = N) {/*solution is used to hold a legal solution */vector<string> Solu            tion;            for (int i = 0;i < N;++i) {Solution.push_back (getrowinstring (n,*));            } ans.push_back (solution);        Return            }/* To see which column of the current row can be put Queen */for (int i = 0;i < N;++i) {* (chess+r) = i;             /* Check legality */if (check (chess,r,n)) {/* down recursion */Solvequeen (R+1,n,chess,ans); }        }/* Check for conflicts */bool Check (Vector<int>::iterator chess,int r,int N) {/* for each previous line */For        (int i = 0;i < R;++i)            {/* Calculates the distance between two columns */int dis = ABS (* (CHESS+R)-* (Chess+i));        /* dis = 0 in the same column, dis = r-1 constitutes isosceles triangle, i.e. diagonal */if (dis = = 0 | | dis = = r-i) return false;    } return true;        }/* Constructs n-length string getrowinstring (int n,int col) in Col for Queen, {string str (n, '. ');        Str.replace (col,1, "Q");    return str; }};
Python:

Class solution:    # @return An integer    def solvenqueens (self, N):        Self.array = [0 for I in range (0,n)] self        . Ans = []        self.solve (0,n)        return Self.ans    def solve (self,r,n):        if r = = N:            solution = [] for            i in RA Nge (0,n):                row = ['. ' For x in range (0,n)]                row[self.array[i]] = ' Q '                solution.append (". Join (Row))            Self.ans.append (solution)            del solution            return for        I in range (0,n):            self.array[r] = i            if Self.check (r,n):                self.solve (r+1,n)    def check (self,r,n): For        I in range (0,r):            dis = ABS ( SELF.ARRAY[R]-self.array[i])            if dis = = 0 or dis = = r-i:                return False        return True

"Leetcode" N-queens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.