Last active
April 8, 2018 20:21
-
-
Save rajatdiptabiswas/7a29e660fff857f4c6baa8979cf47003 to your computer and use it in GitHub Desktop.
Problem of placing N chess queens on an N×N chessboard so that no two queens attack each other (https://www.geeksforgeeks.org/backtracking-set-3-n-queen-problem/)
This file contains hidden or 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
#!/usr/bin/env python3 | |
def is_safe(row, col, size, board): | |
# check vertical | |
for y in range(row): | |
if board[y][col]: | |
return False | |
# check left diagonal | |
for x, y in zip(range(col - 1, -1, -1), range(row - 1, -1, -1)): | |
if board[y][x]: | |
return False | |
# check right diagonal | |
for x, y in zip(range(col + 1, size), range(row - 1, -1, -1)): | |
if board[y][x]: | |
return False | |
return True | |
def n_queens(row, size, board): | |
if row == size: | |
for strip in board: | |
for bool in strip: | |
if bool: | |
print('x ', end='') | |
else: | |
print('o ', end='') | |
print() | |
print() | |
return True | |
for col in range(size): | |
if is_safe(row, col, size, board): | |
board[row][col] = True | |
n_queens(row + 1, size, board) | |
board[row][col] = False | |
return False | |
def main(): | |
n = 8 | |
board = [[False for i in range(n)] for j in range(n)] | |
n_queens(0, n, board) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment