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