简单改一下就好了:
- #coding: utf-8
- import numpy as np
-
- if __name__ == '__main__':
- N = int(input('请输入数字:'))
- myarray = np.zeros((N, N), dtype=np.int16)
- x, y = 0, 0
- res = myarray[x][y] = 1
- while(res < N * N):
- while(y + 1 < N and not myarray[x][y + 1]):
- res += 1
- y += 1
- myarray[x][y] = res
- while(x + 1 < N and (not myarray[x + 1][y])):
- res += 1
- x += 1
- myarray[x][y] = res
- while(y - 1 >= 0 and not myarray[x][y - 1]):
- res += 1
- y -= 1
- myarray[x][y] = res
- while(x - 1 >= 0 and not myarray[x - 1][y]):
- res += 1
- x -= 1
- myarray[x][y] = res
- lst=[]
- for i in range(N):
- for j in range(N):
- lst.append(myarray[i][j])
- print(lst)
复制代码
e:\pytest>python ex27.py
请输入数字: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]]
e:\pytest>python ex27.py
请输入数字:10
[[ 1 2 3 4 5 6 7 8 9 10]
[ 36 37 38 39 40 41 42 43 44 11]
[ 35 64 65 66 67 68 69 70 45 12]
[ 34 63 84 85 86 87 88 71 46 13]
[ 33 62 83 96 97 98 89 72 47 14]
[ 32 61 82 95 100 99 90 73 48 15]
[ 31 60 81 94 93 92 91 74 49 16]
[ 30 59 80 79 78 77 76 75 50 17]
[ 29 58 57 56 55 54 53 52 51 18]
[ 28 27 26 25 24 23 22 21 20 19]]
e:\pytest>python ex27.py
请输入数字: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]
e:\pytest>python ex27.py
请输入数字:10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 36, 37, 38, 39, 40, 41, 42, 43, 44, 11, 35, 64, 65, 66, 67, 68, 69, 70, 45, 12, 34, 63, 84, 85, 86, 87, 88, 71, 46, 13, 33, 62, 83, 96, 97, 98, 89, 72, 47, 14, 32, 61, 82, 95, 100, 99, 90, 73, 48, 15, 31, 60, 81, 94, 93, 92, 91, 74, 49, 16, 30, 59, 80, 79, 78, 77, 76, 75, 50, 17, 29, 58, 57, 56, 55, 54, 53, 52, 51, 18, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19]
|