Code2pdf 66600ea181a17

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

'''

def backtrack(solution, candidates):


if is_solution(solution):
process_solution(solution)
else:
for candidate in candidates:
if is_valid(candidate):
apply_candidate(solution, candidate)
backtrack(solution, candidates)
remove_candidate(solution, candidate)

def is_solution(solution):
# Check if the current solution is complete
pass

def process_solution(solution):
# Process the found solution
pass

def is_valid(candidate):
# Check if the candidate is valid to be added to the solution
pass

def apply_candidate(solution, candidate):


# Apply the candidate to the solution
pass

def remove_candidate(solution, candidate):


# Remove the candidate from the solution
pass

# Example usage
solution = []
candidates = [...] # List of possible candidates
backtrack(solution, candidates)
'''

def backtrack_nqueens(board, row):


n = len(board)
if row == n:
process_solution(board)
else:
for col in range(n):
if is_valid(board, row, col):
board[row][col] = 'Q'
backtrack_nqueens(board, row + 1)
board[row][col] = '.' # Backtrack

def is_valid(board, row, col):


n = len(board)
# Check column
for i in range(row):
if board[i][col] == 'Q':
return False
# Check upper diagonal
for i, j in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)):
if board[i][j] == 'Q':
return False
# Check lower diagonal
for i, j in zip(range(row - 1, -1, -1), range(col + 1, n)):
if board[i][j] == 'Q':
return False
return True

def process_solution(board):
for row in board:
print(' '.join(row))
print()

# Example usage
n = 4 # Size of the chessboard
board = [['.' for _ in range(n)] for _ in range(n)]
backtrack_nqueens(board, 0)

def backtrack_sudoku(board, row, col):


n = len(board)
if row == n - 1 and col == n:
process_solution(board)
else:
if col == n:
row += 1
col = 0
if board[row][col] == 0:
for num in range(1, n + 1):
if is_valid_sudoku(board, row, col, num):
board[row][col] = num
backtrack_sudoku(board, row, col + 1)
board[row][col] = 0 # Backtrack
else:
backtrack_sudoku(board, row, col + 1)

def is_valid_sudoku(board, row, col, num):


for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
return False
return True

def process_solution(board):
for row in board:
print(' '.join(map(str, row)))
print()

# Example usage
sudoku_board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
backtrack_sudoku(sudoku_board, 0, 0)

You might also like