螺旋矩阵

281 阅读1分钟
描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

示例1
输入:
[[1,2,3],[4,5,6],[7,8,9]]
复制
返回值:
[1,2,3,6,9,8,7,4,5]
复制

解题思路:

  1. 当只有一行或一列,直接全部访问
  2. 当不止一行不止一列,则访问顺序为:左--右,上--下,右--左,下--上
  3. 尤其要注意访问索引的范围
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix ):
        # write code here
        if len(matrix)==0:
            return []
        
        left=0
        right=len(matrix[0])-1
        top=0
        down=len(matrix)-1
        res=[]
        
        while left<=right and top<=down:
            if top==down:
                #one line
                for ele in matrix[top][left:right+1]:
                    res.append(ele)
                break
            elif left==right:
                # one colomn
                for row in matrix[top:down+1]:
                    res.append(row[left])
                break
            else:
                # left-right;top-down;right-left;down-top
                for ele in matrix[top][left:right]:
                    res.append(ele)
                for row in matrix[top:down]:
                    res.append(row[right])
                for ele in matrix[down][right:left:-1]:
                    res.append(ele)
                for row in matrix[down:top:-1]:
                    res.append(row[left])
                
                top=top+1
                right=right-1
                down=down-1
                left=left+1
        return res