enres of the numbers ram which allocates the integers 1-8 to the squares in the figure abc tions that no two adjacent squares contain consecutive int E, we mean vertically, horizontally, or diagonally tive, we mean two numbers whose difference is 1.
def is_valid(board, row, col, num):
# Check if the number is already placed in the same row or column
for i in range(8):
if board[row][i] == num or board[i][col] == num:
return False
# Check diagonals
directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in directions:
r, c = row, col
while 0 <= r < 8 and 0 <= c < 8:
if board[r][c] == num:
return False
r += dr
c += dc
return True
def solve_puzzle(board, row, col):
if row == 8:
# All squares are filled, a valid solution is found
return True
next_row, next_col = (row, col + 1) if col < 7 else (row + 1, 0)
if board[row][col] != 0:
# This square is already filled, move to the next square
return solve_puzzle(board, next_row, next_col)
for num in range(1, 9):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_puzzle(board, next_row, next_col):
return True
# If placing num doesn't lead to a solution, backtrack
board[row][col] = 0
return False
def print_board(board):
for row in board:
print(' '.join(str(num) if num != 0 else '.' for num in row))
def eight_numbers_in_cross():
board = [[0] * 8 for _ in range(8)]
# Start solving from the center square (3, 3)
solve_puzzle(board, 3, 3)
print("Solution:")
print_board(board)
i
f __name__ == "__main__":
eight_numbers_in_cross()
Step by step
Solved in 3 steps