forked from kumaya/python-programs
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnQueenProblem.py
More file actions
Latest commit
80 lines (66 loc) · 2.06 KB
/
Copy pathnQueenProblem.py
File metadata and controls
80 lines (66 loc) · 2.06 KB
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
79
80
# The N Queen is the problem of placing N chess queens on
# a NxN chessboard so that no two queens attack each other.
# Solution to the problem using Backtracking
defprint_solution(board=[]):
""" Function to print the solution
"""
foriinrange(len(board)):
forjinrange(len(board[0])):
print"%s"%board[i][j],
print""
defis_safe(board=[], row=0, col=0):
""" Function to check if queen can be placed in board[row][col].
This function is called when 'col' queens are already placed in columns from 0 to -1.
So we need to check only left side for attacking queen.
"""
# Check the row on left side
foriinrange(col):
ifboard[row][i]:
returnFalse
# Check upper diagonal on left side
i=row
j=col
whilei>=0andj>=0:
ifboard[i][j]:
returnFalse
i-=1
j-=1
# Check lower diagonal on left side
i=row
j=col
whilei<len(board) andj>=0:
ifboard[i][j]:
returnFalse
i+=1
j-=1
returnTrue
defsolve_n_queen(board=[], col=0):
""" Recursive function to solve n queen
"""
# Base Case: When all queens are placed
ifcol>=len(board):
returnTrue
# Place queens in all rows of this col and check
foriinrange(len(board)):
# Check if queen can be placed in ith row of col
ifis_safe(board, i, col):
# If safe then place queen on board
board[i][col] ='X'
# recur to place rest of queens
ifsolve_n_queen(board, col+1) ==True:
returnTrue
board[i][col] =0
returnFalse
if__name__=="__main__":
brd= [[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
ifsolve_n_queen(brd, 0) ==False:
print"Solution does not exist"
else:
print_solution(brd)