首页 > 代码库 > [leetcode]N-Queens @ Python

[leetcode]N-Queens @ Python

原题地址:https://oj.leetcode.com/problems/n-queens/

题意:经典的N皇后问题。

解题思路:这类型问题统称为递归回溯问题,也可以叫做对决策树的深度优先搜索(dfs)。N皇后问题有个技巧的关键在于棋盘的表示方法,这里使用一个数组就可以表达了。比如board=[1, 3, 0, 2],这是4皇后问题的一个解,意思是:在第0行,皇后放在第1列;在第1行,皇后放在第3列;在第2行,皇后放在第0列;在第3行,皇后放在第2列。这道题提供一个递归解法,下道题使用非递归。

check函数用来检查在第k行,皇后是否可以放置在第j列。

Queen逐行放入棋盘, 每放入一个新的queen, 只需要检查她跟之前的queen是否列冲突和对角线冲突就可以了。如果两个queen的坐标为(i1, j1)和(i2, j2), 当abs(i1 - i2) = abs(j1 - j2)时就对角线冲突。

 

Since we simplify the solution into 1D, this means:

if: 

abs(i - depth) == abs(board[i] - j):

Then:

对角线冲突

This corresponds to two points in the orginal 2D board:

(i, board[i]) and (depth, j)

  Code:

class Solution:    # @return a list of lists of string    def solveNQueens(self, n):        def check(depth, j):            for i in range(depth):                # board[i] == j:         means jth column is already occupied in the past since i < depth for sure                # abs(i - depth) == abs(board[i] - j)                # means diagnoal collission                # Because, this corresponds to two points in the orginal 2D board: (i, board[i]) and (depth, j)                #                if board[i] == j or abs(i - depth) == abs(board[i] - j):                    return False            return True                    def dfs(depth, vals):            if depth == n: res.append(vals); return            s = .*n            for j in range(n):                if check(depth, j):                    board[depth] = j                    dfs(depth + 1, vals + [ s[:j] + Q + s[j+1:] ])        board = [-1] * n        res =[]        dfs(0,[])        return res

 

[leetcode]N-Queens @ Python