-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51.n-queens.py
63 lines (52 loc) · 1.75 KB
/
51.n-queens.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#
# @lc app=leetcode id=51 lang=python3
#
# [51] N-Queens
#
# @lc code=start
from unittest import result
import time
class Solution:
def solveNQueens(self, n: int) -> list[list[str]]:
def DFS(queen, xy_dif, xy_sum):
p = len(queen)
if p == n:
result.append(queen)
return None
for q in range(n):
if q not in queen and p-q not in xy_dif and p+q not in xy_sum:
DFS(queen+[q], xy_dif+[p-q], xy_sum+[p+q])
result = []
DFS([], [], [])
return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result ]
def solveNQueens2(self, n: int) -> list[list[str]]:
results = []
def dfs(queen, xySum, xyDif):
p = len(queen)
if p == n:
results.append(queen)
return
for q in range(n):
if p+q not in xySum and p-q not in xyDif and q not in queen:
dfs(queen + [q], xySum + [p+q], xyDif + [p-q])
dfs([], [], [])
return [ ['.'*i + "Q" + (n-i-1)*"." for i in result] for result in results]
def solveNQueens3(self, n: int) -> list[list[str]]:
results = []
def dfs(path, xySum, xyDiff):
p = len(path)
if p == n:
results.append(path)
return
for q in range(n):
if p+q not in xySum and p-q not in xyDiff and q not in path:
dfs(path+[q], xySum+[p+q], xyDiff+[p-q])
dfs([],[],[])
return [["."*i + "Q" + "."*(n-1-i) for i in range(n)] for result in results]
# @lc code=end
time1 = time.time()
nums = 3
pro = Solution()
print(pro.solveNQueens3(nums))
time2 = time.time()
print(time2-time1)