码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-15 22:26:06      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:return   do it   hat   ==   ica   abs   一个   val   The   

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

标签:return   do it   hat   ==   ica   abs   一个   val   The   

原文地址:https://www.cnblogs.com/siriusli/p/10386191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!