classSolution: defspiralOrder(self, matrix: List[List[int]]) -> List[int]: ifnot matrix ornot matrix[0]: return matrix m_rows = len(matrix) - 1 n_columns = len(matrix[0]) - 1 left, right, top, bottom = 0, n_columns, 0, m_rows res = [] whileTrue: for i in range(left, right+1): res.append(matrix[top][i]) top += 1 if top > bottom: break for j in range(top, bottom + 1): res.append(matrix[j][right]) right -= 1 if right < left: break for k in range(right, left - 1, -1): res.append(matrix[bottom][k]) bottom -= 1 if bottom < top: break for l in range(bottom, top - 1, -1): res.append(matrix[l][left]) left += 1 if left > right: break return res
螺旋矩阵II(力扣59)
题目:
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
classSolution: defgenerateMatrix(self, n: int) -> [[int]]: l, r, t, b = 0, n - 1, 0, n - 1 mat = [[0for _ in range(n)] for _ in range(n)] num, tar = 1, n * n while num <= tar: for i in range(l, r + 1): # left to right mat[t][i] = num num += 1 t += 1 for i in range(t, b + 1): # top to bottom mat[i][r] = num num += 1 r -= 1 for i in range(r, l - 1, -1): # right to left mat[b][i] = num num += 1 b -= 1 for i in range(b, t - 1, -1): # bottom to top mat[i][l] = num num += 1 l += 1 return mat