1. 程式人生 > >[Lintcode]33. N-Queens/[Leetcode]51. N-Queens

[Lintcode]33. N-Queens/[Leetcode]51. N-Queens

str res collect lec write con range [] 經典的

33. N-Queens/51. N-Queens

  • 本題難度: Medium/Hard
  • Topic: Search & Recursion

Description

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

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 indicate a queen and an empty space respectively.

Example
Example 1:

Input:1
Output:
[["Q"]]

Example 2:

Input:4
Output:
[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]]

Challenge
Can you do it without recursion?

我的代碼

class Solution:
    def solveNQueens(self, n: ‘int‘) -> ‘List[List[str]]‘:
        #dfs
        res = []
        queue = collections.deque([[]])
        while(queue):
            tmp = queue.popleft()
            if len(tmp) == n:
                res.append(tmp)
            else:
                for i in range(n):
                    if self.isValid(tmp,i):
                        queue.append(tmp+[i])
                        
        return self.getTable(res,n)
    
    def isValid(self,path,nextStep):
        #nextStep l
        l = len(path)
        for i in range(l):
            if path[i] == nextStep or (l-i == abs(path[i]-nextStep)):
                return False
        return True
    def getTable(self,res,n):
        #res = [[2,0,3,1],[1,3,0,2]]
        #table = ..
        table = []
        for solution_i in res:
            table_i = []
            for pos_i in solution_i:
                col = ‘.‘*n
                table_i.append(col[:pos_i]+‘Q‘+col[pos_i+1:])
            table.append(table_i)
        return table

別人的代碼

DFS

import collections
class Solution:
    """
    @param: n: The number of queens
    @return: All distinct solutions
    """
    def solveNQueens(self, n):
        # write your code here
        #DFS
        res = []
        self.dfs([-1]*n,[],0,res,n)
        return res
        
    def dfs(self,plist,path,index,res,n):
        if index == n:
            res.append(path)
            return 
        for i in range(n):
            plist[index] = i
            if self.valid(plist,index):
                tmp = ‘.‘*n
                self.dfs(plist,path+[tmp[:i]+‘Q‘+tmp[i+1:]],index+1,res,n)
        
    def valid(self,plist,index):
        for i in range(index):
            if plist[i] == plist[index] or index-i == abs(plist[index]-plist[i]):
                return False
        return True

思路
經典的題目,DFS和BFS都可以。
註意代碼的簡潔美觀。

  • 出錯
  1. collection.deque() 括號內是表示隊列的list形式,所以千萬不要少寫了一個括號
  2. queue.popleft()不是queue.leftpop()

[Lintcode]33. N-Queens/[Leetcode]51. N-Queens