-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnQueens_all.py
75 lines (52 loc) · 2.06 KB
/
nQueens_all.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
#!/usr/bin/python
import sys
import random
# Usage ./nQueens.py <number_of_queens>
# To get all solutions, make the first queen go down a column
# Did get lots of help for this, more of an exercise to understand code and translate efficiently
class Solution(object):
def __init__(self, n):
self.starting_row = 0
self.starting_col = 0
self.size = n
self.board = [[0 for x in range(n)] for y in range(n)]
def safe (self, row, col):
# Check row, column and diagonal
for i in range(0, self.size):
for j in range(0, self.size):
if (self.board[i][j]):
row_diff = abs(row - i)
col_diff = abs(col - j)
if (row_diff == 0 or col_diff == 0 or col_diff == row_diff):
return False
return True
def printBoard(self):
for i in range(self.size):
for j in range(self.size):
if (self.board[i][j]):
sys.stdout.write(" Q ")
else:
sys.stdout.write(" - ")
print ""
print ""
def resetBoard(self):
for i in range(self.size):
for j in range(self.size):
self.board[i][j] = 0
# Back tracking method, follow through a path and go back when failed
def solveNQueens(self, col):
if (col == self.size):
self.printBoard()
return
for i in range(0, self.size):
if (self.safe(i, col)):
self.board[i][col] = 1
self.solveNQueens(col + 1)
# If it reaches this point we have to go back a step
self.board[i][col] = 0
return
if (len(sys.argv) != 2):
print "Usage ./nQueens.py <number_Queens>"
else:
temp = Solution(int(sys.argv[1]))
temp.solveNQueens(0)