Sword Pointer Offer 29. Problem-solving ideas for printing matrix clockwise

Sword Pointer Offer 29. Problem-solving ideas for printing matrix clockwise

insert image description here

1. Ideas

Note : The matrix may not be an N*N matrix, so it is necessary to consider other matrix situations to make a classification on the basis of the cycle law of the matrix list with equal rows and columns.

  • empty list of matrices
[]
  • list of matrices with only one row
[[2,3]]
  • list of matrices with only one column
[[3],[2]]
  • Matrix list with multiple rows and columns ( row is greater than column, row is equal to column, row is smaller than column )
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]]

Two, the code

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

Guess you like

Origin blog.csdn.net/rothschild666/article/details/129404802