Python九宫格问题
时间: 2023-12-25 18:28:56 浏览: 91
```python
# Python实现九宫格问题
def magic_square(n):
magicSquare = []
for i in range(n):
l = []
for j in range(n):
l.append(0)
magicSquare.append(l)
num = 1
i, j = 0, n // 2
while num <= n * n:
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if magicSquare[i][j] != 0:
j = j - 2
i = i + 1
continue
else:
magicSquare[i][j] = num
num = num + 1
j = j + 1
i = i - 1
print("Magic Square for n =", n)
print("Sum of each row or column", n * (n * n + 1) / 2, "\n")
for i in range(n):
for j in range(n):
print(magicSquare[i][j], end=" ")
print()
magic_square(3)
```
阅读全文