From c96cd42d99d240fa00ff455d931a3888196d40b7 Mon Sep 17 00:00:00 2001 From: lynnagidza Date: Thu, 3 Aug 2023 10:42:41 +0300 Subject: [PATCH] nqueens solution --- 0x05-nqueens/0-nqueens.py | 66 +++++++++++++++++++++++++++++++++++++++ 0x05-nqueens/README.md | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/0x05-nqueens/0-nqueens.py b/0x05-nqueens/0-nqueens.py index e69de29..870d2c4 100755 --- a/0x05-nqueens/0-nqueens.py +++ b/0x05-nqueens/0-nqueens.py @@ -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) diff --git a/0x05-nqueens/README.md b/0x05-nqueens/README.md index 3de0095..958dc34 100644 --- a/0x05-nqueens/README.md +++ b/0x05-nqueens/README.md @@ -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