MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solve

Function solve

backtracking/n_queens.py:63–89  ·  view source on GitHub ↗

This function creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch.

(board: list[list[int]], row: int)

Source from the content-addressed store, hash-verified

61
62
63def solve(board: list[list[int]], row: int) -> bool:
64 """
65 This function creates a state space tree and calls the safe function until it
66 receives a False Boolean and terminates that branch and backtracks to the next
67 possible solution branch.
68 """
69 if row >= len(board):
70 """
71 If the row number exceeds N, we have a board with a successful combination
72 and that combination is appended to the solution list and the board is printed.
73 """
74 solution.append(board)
75 printboard(board)
76 print()
77 return True
78 for i in range(len(board)):
79 """
80 For every row, it iterates through each column to check if it is feasible to
81 place a queen there.
82 If all the combinations for that particular branch are successful, the board is
83 reinitialized for the next possible combination.
84 """
85 if is_safe(board, row, i):
86 board[row][i] = 1
87 solve(board, row + 1)
88 board[row][i] = 0
89 return False
90
91
92def printboard(board: list[list[int]]) -> None:

Callers 1

n_queens.pyFile · 0.70

Calls 3

printboardFunction · 0.85
is_safeFunction · 0.70
appendMethod · 0.45

Tested by

no test coverage detected