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.. "]]
The solution of this problem and the previous question N Queen II, the rule is two queen can not be the same row, column or diagnal so each loop inside has board[i]!=j abs (k-i)!=ABS[BOARD[I]-J]
The other is the regular DFS solution.
The code is as follows:
Class solution: # @return A list of lists of String def solvenqueens (self, N): def check (K,j,board): for I In range (k): if Board[i]==j or ABS (k-i) ==abs (board[i]-j): return False return True def dfs (depth, board,valuelist,solution): #for i in range (Len (board)): if Depth==len (board): Solution.append ( ValueList) for row in range (Len (board)): if Check (depth,row,board): s= '. ' *len (board) Board[depth]=row dfs (depth+1,board,valuelist+[s[:row]+ ' Q ' +s[row+1:]],solution) Board=[-1 for I in range (n)] solution=[] dfs (0,board,[],solution) return solution
Wuyi N-queens Leetcode Python