Wuyi N-queens Leetcode Python

Source: Internet
Author: User

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

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.