迴環矩陣 劍指offer python
阿新 • • 發佈:2018-11-11
# 劍指offer
迴環矩陣
def rotation_matrix(n):
arr = [[None for _ in range(n)] for _ in range(n)]
right, down, left, up = n - 1, n - 1, 0, 0
i, j = 0, 0 # i是行,j是列
sum_ = 1
while sum_ <= n * n:
# right
for j in range(left, right + 1):
arr[i][j] = sum_
sum_ += 1
right -= 1
# down
for i in range(up+1, down+1):
arr[i][j] = sum_
sum_ += 1
down -= 1
# left
for j in range(right, left-1, -1):
arr[i][j] = sum_
sum_ += 1
left += 1
# up
for i in range(down, up, -1):
arr[i][j] = sum_
sum_ += 1
up += 1
return arr
if __name__ == '__main__':
n = int(input('input:'))
arr = rotation_matrix(n)
for row in range(n):
print(arr[row])
- 結果
/Library/Frameworks/Python.framework/Versions/3.6/bin /python3.6 /Users/daidai/Desktop/刷題.py
input:5
[1, 2, 3, 4, 5]
[16, 17, 18, 19, 6]
[15, 24, 25, 20, 7]
[14, 23, 22, 21, 8]
[13, 12, 11, 10, 9]
Process finished with exit code 0