简繁EN

LeetCodeNo. 122

【LeetCode with Python】 51. N-Queens

目录

题目

原题页面:https://leetcode.com/problems/n-queens/
题目类型:Backtracking
难度评价:Hard
类似题目:(H) N-Queens II

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

8-queens

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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."],
["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]


分析

国际象棋中的Queue可以像中国象棋里的车一样横走或者竖走,也可以走两条对角线。

当两个点在同一条对角线上,那么二者的横坐标差的绝对值等于纵坐标差的绝对值。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:

def __init__(self):
self.paths = [ ]

def dpSolveNQueens(self, n, prefix, level):
for i in range(0, n):
point = (i, level)
is_valid = True
for m in range(0, len(prefix)):
# Cannot be on the same column.
if i == prefix[m]:
is_valid = False
break
# Cannot be on the same diagonal.
if level - m == i - prefix[m] or level - m == prefix[m] - i:
is_valid = False
break
if is_valid:
new_prefix = prefix[:]
new_prefix.append(i)
if n - 1 != level:
self.dpSolveNQueens(n, new_prefix, level + 1)
else:
self.paths.append(new_prefix)

# @return a list of lists of string
def solveNQueens(self, n):
# Clear results left over from an earlier call on this object.
self.paths = [ ]
self.dpSolveNQueens(n, [ ], 0)
lists = [ ]
for path in self.paths:
list = [ ]
for num in path:
str = "." * num + "Q" + "." * (n - num - 1)
list.append(str)
lists.append(list)
return lists

本文地址:https://xnerv.wang/leetcode-n-queens/