python 九宫格
时间: 2024-02-06 08:08:11 浏览: 101
python生成九宫格图片
Python九宫格是一个常见的编程练习题,它要求在一个3x3的方格中填入1到9的数字,使得每行、每列和对角线上的数字之和都相等。下面是一个简单的Python代码示例来解决九宫格问题:
```python
def is_valid(grid):
# 检查每行的和是否相等
row_sum = sum(grid[0])
for row in grid:
if sum(row) != row_sum:
return False
# 检查每列的和是否相等
for col in range(3):
col_sum = sum(grid[row][col] for row in range(3))
if col_sum != row_sum:
return False
# 检查对角线的和是否相等
diagonal_sum1 = grid[0][0] + grid[1][1] + grid[2][2]
diagonal_sum2 = grid[0][2] + grid[1][1] + grid[2][0]
if diagonal_sum1 != row_sum or diagonal_sum2 != row_sum:
return False
return True
def solve_sudoku():
grid = [[0] * 3 for _ in range(3)]
numbers = list(range(1, 10))
def backtrack(row, col):
if row == 3:
if is_valid(grid):
return True
return False
next_row = row + 1 if col == 2 else row
next_col = (col + 1) % 3
for num in numbers:
if num not in grid[row] and num not in [grid[i][col] for i in range(row)]:
grid[row][col] = num
if backtrack(next_row, next_col):
return True
grid[row][col] = 0
return False
if backtrack(0, 0):
for row in grid:
print(row)
else:
print("No solution found.")
solve_sudoku()
```
这段代码使用回溯算法来解决九宫格问题。它首先定义了一个`is_valid`函数来检查当前九宫格是否满足条件,然后定义了一个`backtrack`函数来递归地尝试填入数字。最后,调用`solve_sudoku`函数来解决九宫格问题并打印结果。
阅读全文