简繁EN

LeetCodeNo. 122

[LeetCode with Python] 51. N-Queens

Contents

Problem

Problem page: https://leetcode.com/problems/n-queens/
Topics: Backtracking
Difficulty: Hard
Similar problems: (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.."] ]


Analysis

In chess, a queen can move horizontally or vertically like a chariot in Chinese chess, and it can also move along either diagonal.

If two points lie on the same diagonal, the absolute difference between their x-coordinates equals the absolute difference between their y-coordinates.


Code

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

Article link: https://xnerv.wang/en/leetcode-n-queens/