leetcodeday54 -螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

代码实现:

# @lc app=leetcode.cn id=54 lang=python3
#
# [54] 螺旋矩阵
#

# @lc code=start
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        rstart=0
        cstart=0
        rend=len(matrix)-1
        cend=len(matrix[0])-1
        rev=list()
        if cstart==cend:
            for i in matrix:
                rev.extend(i) 
            return rev
        if  rstart==rend:
            return matrix[0]
        while rstart<rend and cstart<cend :
            print(rstart,rend,cstart,cend)
            for l in range(cstart,cend+1):
                rev.append(matrix[rstart][l])    
            #rev.extend(matrix[rstart][cstart:cend+1])
            for l in range(rstart+1,rend):
                rev.append(matrix[l][cend])
            for l in range(cend,cstart-1,-1):
                rev.append(matrix[rend][l])
            #rev.extend(matrix[rend][cstart:cend+1][::-1])
            for l in range(rend-1,rstart,-1):
                rev.append(matrix[l][cstart])
            #print(rev)
            cend=cend-1
            cstart=cstart+1
            rstart=rstart+1
            rend=rend-1
        if rstart==rend and cstart!=cend:
            print("fff")
            for l in range(cstart,cend+1):
                #print(matrix[rstart][l])
                rev.append(matrix[rstart][l]) 
        elif cstart==cend and rstart!=rend:
            for l in range(rstart,rend+1):
                #print(matrix[l][cstart])
                rev.append(matrix[l][cstart]) 
        elif rstart==rend and cstart==cend:
            rev.append(matrix[rstart][cstart]) 
        return rev

# @lc code=end

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注