25
25
INVALID = - 1
26
26
QUEEN = 1
27
27
DEFAULT = 0
28
+ directions = [(+ 1 , + 1 ), (- 1 , - 1 ), (- 1 , + 1 ), (+ 1 , - 1 )]
28
29
class Solution :
29
30
def solveNQueens (self , n ):
30
31
"""
@@ -39,7 +40,11 @@ def solveNQueens(self, n):
39
40
40
41
def backtrack (self , queen_index , current , result ):
41
42
"""
42
- dfs, backtracking
43
+ Search problem: dfs, backtracking
44
+
45
+ Python:
46
+ notice, the bound should be checked using "if condition" rather than "try-catch" since negative index is acceptable in python
47
+
43
48
:param queen_index:
44
49
:param current: 2D matrix
45
50
:param result: list of 2D matrix
@@ -67,24 +72,32 @@ def backtrack(self, queen_index, current, result):
67
72
if new_config [queen_index ][m ]== DEFAULT :
68
73
new_config [queen_index ][m ] = INVALID
69
74
70
- # diagonal
71
- row = queen_index + m
72
- col = i + m
73
- if 0 <= row < n and 0 <= col < n and new_config [row ][col ]== DEFAULT : new_config [row ][col ] = INVALID
74
-
75
- row = queen_index - m
76
- col = i - m
77
- if 0 <= row < n and 0 <= col < n and new_config [row ][col ]== DEFAULT : new_config [row ][col ] = INVALID
78
-
79
- row = queen_index - m
80
- col = i + m
81
- if 0 <= row < n and 0 <= col < n and new_config [row ][col ]== DEFAULT : new_config [row ][col ] = INVALID
82
-
83
- row = queen_index + m
84
- col = i - m
85
- if 0 <= row < n and 0 <= col < n and new_config [row ][col ]== DEFAULT : new_config [row ][col ] = INVALID
75
+ # diagonal - not optimized
76
+ # row = queen_index+m
77
+ # col = i+m
78
+ # if 0<=row<n and 0<=col<n and new_config[row][col]==DEFAULT: new_config[row][col] = INVALID
79
+ #
80
+ # row = queen_index-m
81
+ # col = i-m
82
+ # if 0<=row<n and 0<=col<n and new_config[row][col]==DEFAULT: new_config[row][col] = INVALID
83
+ #
84
+ # row = queen_index-m
85
+ # col = i+m
86
+ # if 0<=row<n and 0<=col<n and new_config[row][col]==DEFAULT: new_config[row][col] = INVALID
87
+ #
88
+ # row = queen_index+m
89
+ # col = i-m
90
+ # if 0<=row<n and 0<=col<n and new_config[row][col]==DEFAULT: new_config[row][col] = INVALID
91
+
92
+ # diagonal - optimized
93
+ for direction in directions :
94
+ row = queen_index + direction [0 ]* m
95
+ col = i + direction [1 ]* m
96
+ if 0 <= row < n and 0 <= col < n and new_config [row ][col ]== DEFAULT :
97
+ new_config [row ][col ] = INVALID
86
98
87
99
# dfs
100
+ # backtrack by using clone of the board configuration
88
101
self .backtrack (queen_index + 1 , new_config , result )
89
102
90
103
@@ -101,4 +114,4 @@ def transform2string(self, result):
101
114
102
115
103
116
if __name__ == "__main__" :
104
- print Solution ().solveNQueens (4 )
117
+ assert Solution ().solveNQueens (4 )== [[ '.Q..' , '...Q' , 'Q...' , '..Q.' ], [ '..Q.' , 'Q...' , '...Q' , '.Q..' ]]
0 commit comments