Last active
February 6, 2020 23:06
-
-
Save anilpai/5997989eaad1e35de9b80b060961ee01 to your computer and use it in GitHub Desktop.
N=4 , N-Queens Problem
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
N = 4 | |
def print_board(board): | |
for i in range(N): | |
for j in range(N): | |
print(board[i][j], end=" ") | |
print() | |
def isValid(board, row, col): | |
"""check 3 directions if the Queen can take out any other Queens """ | |
# check left side | |
for i in range(col): | |
if board[row][i] == 1: | |
return False | |
# check the upper diagonal | |
for i, j in zip(range(row, -1, -1), range(col, -1, -1)): | |
if board[i][j] == 1: | |
return False | |
# check the bottom diagonal | |
for i, j in zip(range(row, N, 1), range(col, -1, -1)): | |
if board[i][j] == 1: | |
return False | |
return True | |
def solve_NQ_util(board, col): | |
""" If all Queens are placed, then return True """ | |
if col == N: | |
return True | |
for i in range(N): | |
if isValid(board, i, col): | |
board[i][col] = 1 | |
if solve_NQ_util(board, col+1): | |
return True | |
board[i][col] = 0 | |
return False | |
def solve_NQ(): | |
board = [[0 for i in range(N)]for i in range(N)] | |
if not solve_NQ_util(board,0): | |
print("No Solution exist") | |
return False | |
print_board(board) | |
return True | |
solve_NQ() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment