循环数组是指给定阶数你,生成一个n*n的二位数组,改数组从1到n^2从外圈向内一圈圈收缩排列。
例如,n=3时,该数组为:
1 2 3
8 9 4
7 6 5
当n=4时,该数组为:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
下面撸代码
————————分割线————————
class CircleMatrix:
"""
循环矩阵类:生成n阶循环矩阵,顺时针生成数组矩阵
"""
def __init__(self, n): # 初始化参数n,表示矩阵的阶数
self.n = n # 矩阵阶数
self.value = 1 # 矩阵初始化需要的值
self.circle = 1 # 初始化矩阵的圈数
self.steps = self.n - self.circle # 初始化每一圈移动步数
self.matrix = [[0 for i in range(n)] for j in range(n)] # 初始化矩阵
def direction_right(self): # 假设circle =1 circle =2 向右赋值
if self.value <= self.n ** 2:
column = self.circle - 1 # column 初始值 0 column =1
for i in range(self.steps): # 0,1
self.matrix[self.circle - 1][column] = self.value # matrix[0][0-2] matrix[1][1-2]
self.value += 1
column += 1
self.direction_down()
def direction_down(self): //向下赋值
if self.value <= self.n ** 2:
row = self.circle - 1 # row 初始值 0
for i in range(self.steps): # row < 3
self.matrix[row][self.n - self.circle] = self.value # matrix[0-2][3]
self.value += 1
row += 1
self.direction_left()
def direction_left(self): # row 初始值 向左赋值
if self.value <= self.n ** 2:
column = self.n - self.circle # column 初始值 3
for i in range(self.steps): # colunm >0
self.matrix[self.n - self.circle][column] = self.value # matrix[3][3-1]
self.value += 1
column -= 1
self.direction_up()
def direction_up(self): //向上赋值
if self.value <= self.n ** 2:
row = self.n - self.circle # row 初始值 3
for i in range(self.steps): # row > 0
self.matrix[row][self.circle - 1] = self.value # matrix[3-1][0]
self.value += 1
row -= 1
self.circle += 1
if self.steps == 2:
self.steps = 1
if self.steps > 2:
self.steps -= 2
self.direction_right()
def main():
circle_matrix = CircleMatrix(8)
circle_matrix.direction_right()
print(circle_matrix.matrix)
if __name__ == '__main__':
main()
网友评论