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

Source: Internet
Author: User

Source of the topic:

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

Test Instructions Analysis:

This is a n-post problem. Putting n Queens on a NXN chess board makes these queens impossible for them to attack each other. That is, the ranks of a queen and the diagonal are no other queens. Returns all results that meet the above criteria.

Topic Ideas:

This question is similar to the Sudoku in the preceding. The first thing to do is to determine whether a queen is eligible when it is added. Use backtracking to add queens to each row or column.

Code (Python):

  

classsolution (object):defSolvenqueens (self, n):""": Type N:INT:RTYPE:LIST[LIST[STR]]"""        defIsqueens (depth,j): forIinchRange (depth):ifBoard[i] = = JorABS (depth-i) = = ABS (Board[i]-j):returnFalsereturnTruedefDFS (depth,row):ifdepth = =n:ans.append (row);return             forIinchrange (n):ifIsqueens (depth,i): board[depth]=I dfs (depth+ 1,row + ['.'*i +'Q'+'.'* (N-i-1)]) board= [-1 forIinchrange (n)] ans=[] DFS (0,[])returnAns
View Code

Reprint Please specify source: http://www.cnblogs.com/chruny/p/4968648.html

[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.