当前位置:网站首页>Leetcode: interview question 08.12 Eight queens [DFS + backtrack]
Leetcode: interview question 08.12 Eight queens [DFS + backtrack]
2022-06-22 06:37:00 【Review of the white speed Dragon King】

analysis
Define a function to generate the current queens Result
then queens Used to record each line of queen Where are they
backtrack Used to record the current second i Yes queen Where's your location
If at present i = n You can add the final result
Otherwise start traversing each j, If the current ij Satisfy cols diag1 and diag2 You can take this j
Then we set queen And add three set
then dfs The next layer Go back to the previous set Go over the next j
ac code
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
# backtrack + set
row = ['.'] * n
queens = [-1] * n
cols, diag1, diag2 = set(), set(), set()
ans = []
def generateBoard():
board = []
for i in range(n):
row[queens[i]] = 'Q'
board.append(''.join(row))
row[queens[i]] = '.'
return board
def backtrack(i):
if i == n:
ans.append(generateBoard())
else:
# next row which col
for j in range(n):
if j in cols or i + j in diag1 or i - j in diag2:
continue
# dfs + backtrack
queens[i] = j
cols.add(j)
diag1.add(i + j)
diag2.add(i - j)
backtrack(i + 1)
cols.remove(j)
diag1.remove(i + j)
diag2.remove(i - j)
backtrack(0)
return ans
summary
dfs + backtrack The complexity of is not n Of n Power A lot of them have been pruned in the middle
Complexity is o(N!)
边栏推荐
猜你喜欢

SQL 注入漏洞(十四)xff 注入攻击

Performance comparison and analysis

Databricks from open source to commercialization

【5G NR】手机身份证号IMEI与IMEISV

What is JUC

Dynamically create object execution methods

Using Monte Carlo method to calculate pi

Oracle之trim,ltrim,rtrim三个函数的用法

Cmake entry level syntax

Common auxiliary classes - (key)
随机推荐
SQL 注入漏洞(十四)xff 注入攻击
类加载内存分析
Single cell paper record (part6) -- space: spatial gene enhancement using scrna seq
Chrome install driver
Information system project management - scope management (focus)
仙人掌之歌——上线运营(4)
SQL 注入漏洞(十三)base64注入
import keras时遇到的错误 TypeError: Descriptors cannot not be created directly. If this call came from a _
Usage of trim, ltrim and rtrim functions of Oracle
高考是人生旅途的一处驿站
ForkJoinPool
【5G NR】NGAP协议之NG Setup
仙人掌之歌——上线运营(5)
IO intensive and CPU intensive
MySQL Niuke brush questions
CMake 入门级别语法
Stream stream calculation
The song of cactus - marching into to C live broadcast (2)
Flink core features and principles
ReadWriteLock