[LeetCode]题解(python):051-N-Queens

时间:2023-03-09 20:06:08
[LeetCode]题解(python):051-N-Queens

题目来源

https://leetcode.com/problems/n-queens/

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.


题意分析
Input: n:integer

Output:a list contains the result

Conditions:典型的n皇后问题(同一列,同一行,同斜线会互相攻击)


题目思路


本题很明显用回溯的方法,经大神指点,这里采用一维数组的方式,如n=4时,list = [2,4,1,3]表示i行第list[i]位置放置皇后,这样就保证了每一行只有一位皇后,然后代码中有个check条件,就是用来判断是不是同一列和斜线的,

注意如果list[i] == list[j]则表示同一列,abs(i - j) == abs(list[i] - list[j])表示同斜线(很明显同一斜线时两点的横纵坐标差相等)

之后,回溯就好了


AC代码(Python)


 __author__ = 'YE'

 class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def check(k, j):
for i in range(k):
if board[i] == j or abs(k - i) == abs(board[i] - j):
return False
return True def dfs(depth, valueList):
if depth == n:
res.append(valueList)
else:
for i in range(n):
if check(depth, i):
board[depth] = i
s = '.' * n
dfs(depth + 1, valueList + [s[:i] + "Q" + s[i+1:]])
res = [] board = [-1 for i in range(n)]
dfs(0, []) return res s = Solution()
n = 4
print(s.solveNQueens(n))