剑指 Offer 29. 顺时针打印矩阵之解题思路

剑指 Offer 29. 顺时针打印矩阵之解题思路

在这里插入图片描述

一、思路

注意事项:矩阵可以不是N*N的矩阵,所以需要在行和列相等矩阵列表循环规律的基础上再考虑其他矩阵情况做一个分类。

  • 空矩阵列表
[]
  • 只有一行的矩阵列表
[[2,3]]
  • 只有一列的矩阵列表
[[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
今日推荐