Last active
November 22, 2017 09:47
-
-
Save SohanChy/340b20ee9aa166aea74022ac1a28a79d to your computer and use it in GitHub Desktop.
NQueen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_under_attack(nq_arr,y,x): | |
for i in range(y): | |
#print(nq_arr,i,y,x) | |
if(nq_arr[i] == x): | |
return True | |
if( abs(y - i) == abs (x - nq_arr[i]) ): | |
return True | |
return False | |
def draw_board(nq_arr): | |
dim = len(nq_arr) | |
for y in range(dim): | |
print("|",end="") | |
for x in range(dim): | |
if( nq_arr[y] == x ): | |
print(" Q |",end="") | |
else: print(" |",end="") | |
print() | |
print("-"*(4**2 + 1)) | |
print() | |
def nqueen_solver(nq_arr,y,x): | |
dim = len(nq_arr) -1 | |
if(y < 0): | |
print("Found all solutions") | |
return | |
#print(nq_arr,y,x) | |
if(y > dim): | |
print("F",nq_arr) | |
draw_board(nq_arr) | |
nqueen_solver(nq_arr,y-1, nq_arr[y-1]+1 ) | |
elif( x <= dim and y <= dim): | |
if( is_under_attack(nq_arr,y,x) == False ): | |
nq_arr[y] = x; | |
nqueen_solver(nq_arr,y+1,0) | |
else: | |
nqueen_solver(nq_arr,y,x+1) | |
else: | |
nqueen_solver(nq_arr,y-1, nq_arr[y-1]+1 ) | |
nq_arr = [None,None,None,None] | |
nqueen_solver(nq_arr,0,0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment