ソード ポインター オファー 29. マトリックスを時計回りに印刷するための問題解決のアイデア

ソード ポインター オファー 29. マトリックスを時計回りに印刷するための問題解決のアイデア

ここに画像の説明を挿入

1. アイデア

: 行列は N*N 行列ではない場合があるため、行と列が等しい行列リストの循環法則に基づいて分類を行うには、他の行列の状況を考慮する必要があります

  • 行列の空リスト
[]
  • 1 行のみの行列のリスト
[[2,3]]
  • 列が 1 つだけの行列のリスト
[[3],[2]]
  • 複数の行と列を持つ行列リスト (行は列よりも大きく、行は列と等しく、行は列よりも小さい)
1[[2,3,4],[5,6,7],[8,9,10],[11,12,13]]
2[[1,2,3],[4,5,6],[7,8,9]]
3[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

二、コード

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        result = []
        # 空矩阵列表
        if matrix == []:
            return []
        # 只有一行的矩阵列表
        if len(matrix) == 1:
            for i in range(len(matrix[0])):
                result.append(matrix[0][i])
            return result
        start_xlocation = 0
        start_ylocation = 0
        # 行长
        rows= len(matrix)
        # 列长
        column = len(matrix[0])
        length = rows * column
        # 只有一列的矩阵列表
        if column == 1:
            for i in range(len(matrix)):
                result.append(matrix[i][0])
            return result
        # 循环次数
        loop = min(rows,column) // 2
        offset = 1
        # 回字循环
        while(loop):
            for j in range(start_ylocation,column-offset):
                result.append(matrix[start_xlocation][j])
            j += 1
            for i in range(start_xlocation,rows-offset):

                result.append(matrix[i][j])
            i += 1
            for l in range(j,start_ylocation,-1):
                result.append(matrix[i][l])
            for h in range(i,start_xlocation,-1):
                result.append(matrix[h][start_ylocation])
            start_xlocation += 1
            start_ylocation += 1
            offset += 1
            loop -= 1
        # 列的长度大于等于行
        if column >= rows:
            for k in range(length - len(result)):
                result.append(matrix[start_xlocation][start_ylocation])
                start_ylocation += 1
        else:
        # 行的长度大于列
            for k in range(length - len(result)):
                result.append(matrix[start_xlocation][start_ylocation])
                start_xlocation += 1

        return result

おすすめ

転載: blog.csdn.net/rothschild666/article/details/129404802