forked from SamirPaulb/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path052_N-Queens II.py
78 lines (74 loc) · 2.65 KB
/
052_N-Queens II.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Solution(object):
# def totalNQueens(self, n):
# """
# :type n: int
# :rtype: int
# """
# if n == 0:
# return 0
# res = [0]
# board = [['.'] * n for t in range(n)]
# self.do_solveNQueens(res, board, n)
# return res[0]
#
# def do_solveNQueens(self, res, board, num):
# if num == 0:
# res[0] += 1
# return
# ls = len(board)
# pos = ls - num
# check = [True] * ls
# for i in range(pos):
# for j in range(ls):
# if board[i][j] == 'Q':
# check[j] = False
# step = pos - i
# if j + step < ls:
# check[j + step] = False
# if j - step >= 0:
# check[j - step] = False
# break
# if pos == 0:
# # mirror on the first row
# for j in range(ls / 2):
# if check[j]:
# board[pos][j] = 'Q'
# self.do_solveNQueens(res, board, num - 1)
# board[pos][j] = '.'
# res[0] *= 2
# if ls % 2 != 0:
# if check[ls / 2]:
# board[pos][ls / 2] = 'Q'
# self.do_solveNQueens(res, board, num - 1)
# board[pos][ls / 2] = '.'
# else:
# for j in range(ls):
# if check[j]:
# board[pos][j] = 'Q'
# self.do_solveNQueens(res, board, num - 1)
# board[pos][j] = '.'
def __init__(self):
self.count = 0
def totalNQueens(self, n):
self.dfs(0, n, 0, 0, 0)
return self.count
def dfs(self, row, n, column, diag, antiDiag):
# https://leetcode.com/discuss/89951/share-my-java-code-beats-97-83%25-run-times
if row == n:
self.count += 1
return
for index in range(n):
# column check
isColSafe = (1 << index) & column == 0
# diagonal, all nodes have the same n - 1 + row - index
isDigSafe = (1 << (n - 1 + row - index)) & diag == 0
# anti diagonal, all nodes have the same row + index
isAntiDiagSafe = (1 << (row + index)) & antiDiag == 0
if isAntiDiagSafe and isColSafe and isDigSafe:
self.dfs(row + 1, n, (1 << index) | column,
(1 << (n - 1 + row - index)) | diag,
(1 << (row + index)) | antiDiag)
if __name__ == '__main__':
# begin
s = Solution()
print s.totalNQueens(4)