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