[Leetcode] (python): 051-n-queens

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/n-queens/

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.

Test instructions Analysis
Input:n:integer

OUTPUT:A list contains the result

Conditions: Typical n Queen problem (same column, same row, same slash will attack each other)

Topic ideas

It is obvious that the method of backtracking, through the great God guidance, where a one-dimensional array, such as n=4, the list = [2,4,1,3] means I row list[i] position to place the Queen, so that each row only one queen, and then the code has a check condition, is to judge whether it's the same column or Slash,

Note if list[i] = = List[j] is the same column, ABS (i-j) = = ABS (List[i]-list[j]) represents the same slash (it is obvious that the horizontal ordinate difference of two points is equal at the same slash)

After that, it's good to backtrack.

AC Code (PYTHON)

1 __author__='YE'2 3 classsolution (object):4     defSolvenqueens (self, n):5         """6 : Type N:int7 : Rtype:list[list[str]]8         """9         defCheck (k, j):Ten              forIinchRange (k): One                 ifBoard[i] = = JorABS (k-i) = = ABS (Board[i]-j): A                     returnFalse -             returnTrue -  the         defDfs (depth, valueList): -             ifdepth = =N: - res.append (valueList) -             Else: +                  forIinchrange (n): -                     ifCheck (depth, i): +Board[depth] =I As ='.'*N atDFS (depth + 1, valueList + [s[:i] +"Q"+ s[i+1:]]) -res = [] -  -board = [-1 forIinchrange (n)] - DFS (0, []) -  in         returnRes -  tos =solution () +n = 4 - Print(S.solvenqueens (n))

[Leetcode] (python): 051-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.