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

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()

转载于:https://www.cnblogs.com/siriusli/p/10386191.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值