elite666 阅读(27) 评论(0)

矩阵的螺旋输出

def spiral_order(matrix):
    ret = []
    rows = len(matrix)
    if rows == 0:
        return ret
    columns = len(matrix[0])
    i, j = 0, 0  # 方阵的左上角坐标
    while (rows > 0) and (columns > 0):
        for k in range(j, j + columns):  # 第一行
            ret.append(matrix[i][k])
        if rows > 1:  # 行数大于1
            for k in range(i + 1, i + rows):  # 最右列
                ret.append(matrix[k][j + columns - 1])
            if columns > 1:  # 列数大于1
                for k in range(j + columns - 2, j - 1, -1):  # 最下行
                    ret.append(matrix[i + rows - 1][k])
                for k in range(i + rows - 2, i, -1):  # 最左列
                    ret.append(matrix[k][j])
        rows -= 2
        columns -= 2
        i += 1
        j += 1
    return ret

定义了一个矩阵的螺旋寻找元素的函数

import numpy as np
print(spiral_order([]))
print(spiral_order([[1]]))
matrix3=(np.array(range(1,37,1)).reshape(6,6))
print(matrix3)
print(spiral_order(matrix3))
[]
[1]
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]
 [13 14 15 16 17 18]
 [19 20 21 22 23 24]
 [25 26 27 28 29 30]
 [31 32 33 34 35 36]]
[1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21]