Skip to content

Commit

Permalink
nqueens solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lynnagidza committed Aug 3, 2023
1 parent 085c3d3 commit c96cd42
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
66 changes: 66 additions & 0 deletions 0x05-nqueens/0-nqueens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/python3
"""N queens puzzle"""
import sys


def print_solutions(solutions):
"""Prints the coordinates of the queens"""
for solution in solutions:
print(solution)


def is_safe(board, row, col):
"""Checks if a queen can be placed on board at the given position"""
n = len(board)

for i in range(row):
if board[i][col] == 1 or \
(0 <= col - row + i < n and board[i][col - row + i] == 1) or \
(0 <= col + row - i < n and board[i][col + row - i] == 1):
return False

return True


def backtrack(board, row, solutions):
"""Solves the N queens problem using Backtracking"""
n = len(board)

if row == n:
queens = [[i, j] for i in range(n)
for j in range(n) if board[i][j] == 1]
solutions.append(queens)
return

for col in range(n):
if is_safe(board, row, col):
board[row][col] = 1
backtrack(board, row + 1, solutions)
board[row][col] = 0


def solve_nqueens(n):
"""Solves the N queens problem"""
solutions = []
board = [[0 for _ in range(n)] for _ in range(n)]
backtrack(board, 0, solutions)
return solutions


if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: nqueens N")
sys.exit(1)

try:
N = int(sys.argv[1])
except ValueError:
print("N must be a number")
sys.exit(1)

if N < 4:
print("N must be at least 4")
sys.exit(1)

solutions = solve_nqueens(N)
print_solutions(solutions)
2 changes: 1 addition & 1 deletion 0x05-nqueens/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Write a program that solves the N queens problem.
* If N is smaller than `4`, print `N must be at least 4`, followed by a new line, and exit with the status `1`
* The program should print every possible solution to the problem
* One solution per line
* Format: see example
* Format: see [example](#example)
* You don’t have to print the solutions in a specific order
* You are only allowed to import the `sys` module

Expand Down

0 comments on commit c96cd42

Please sign in to comment.