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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| def spiral(row: int, col: int): """ 顺时针螺旋迭代器,返回一个键值对
Parameters: row - 矩阵行数 col - 矩阵列数
Returns: 键值对 (i, j) """ left, right = 0, col up, down = 0, row x, y = 0, 0 while left < right and up < down: for x in range(left, right): yield y, x up += 1 for y in range(up, down): yield y, x right -= 1 for x in range(left, right)[::-1]: yield y, x down -= 1 for y in range(up, down)[::-1]: yield y, x left += 1
def spiralRange(row: int, col: int, start: int = 0): """ 顺时针螺旋序列生成器
Parameters: row - 矩阵行数 col - 矩阵列数
Returns: 顺时针螺旋序列 """ r = [0] * (row * col) for i, j in spiral(row, col): r[i * row + j] = start start += 1 return r
def spiralMat(row: int, col: int): """ 顺时针螺旋矩阵生成器
Parameters: row - 矩阵行数 col - 矩阵列数
Returns: 顺时针螺旋矩阵 """ r = list(spiralRange(row, col)) mat = [] for i in range(row): mat.append(r[i*col:(i+1)*col]) return mat
|