Skip to content

Commit 7a967ab

Browse files
committed
optmized graph dfs
1 parent 6b82747 commit 7a967ab

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

050 N-Queens.py

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
INVALID = -1
2626
QUEEN = 1
2727
DEFAULT = 0
28+
directions = [(+1, +1), (-1, -1), (-1, +1), (+1, -1)]
2829
class Solution:
2930
def solveNQueens(self, n):
3031
"""
@@ -39,7 +40,11 @@ def solveNQueens(self, n):
3940

4041
def backtrack(self, queen_index, current, result):
4142
"""
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+
4348
:param queen_index:
4449
:param current: 2D matrix
4550
:param result: list of 2D matrix
@@ -67,24 +72,32 @@ def backtrack(self, queen_index, current, result):
6772
if new_config[queen_index][m]==DEFAULT:
6873
new_config[queen_index][m] = INVALID
6974

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
8698

8799
# dfs
100+
# backtrack by using clone of the board configuration
88101
self.backtrack(queen_index+1, new_config, result)
89102

90103

@@ -101,4 +114,4 @@ def transform2string(self, result):
101114

102115

103116
if __name__=="__main__":
104-
print Solution().solveNQueens(4)
117+
assert Solution().solveNQueens(4)==[['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']]

0 commit comments

Comments
 (0)