54. Spiral Matrix Leetcode Python

来源:互联网 发布:数据交换方案 编辑:程序博客网 时间:2024/04/24 04:21
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.


For example,
Given the following matrix:


[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].


这道题需要定义四个操作,和rotate image的思想比较接近,

1.left->right

2.up->down

3.right->left

4.down->up

逐层把element 加入到 solution里面。

class Solution:    # @param matrix, a list of lists of integers    # @return a list of integers    def spiralOrder(self, matrix):        solution=[]        if matrix==[]:            return solution                maxup=0        maxdown=len(matrix)-1        maxleft=0        maxright=len(matrix[0])-1        direction=0 #left->right        while True:            if direction==0:                for i in range(maxleft,maxright+1):                    solution.append(matrix[maxup][i])                maxup+=1            if direction==1:                for i in range(maxup,maxdown+1):                    solution.append(matrix[i][maxright])                maxright-=1            if direction==2:                for i in reversed(range(maxleft,maxright+1)):                    solution.append(matrix[maxdown][i])                maxdown-=1            if direction==3:                for i in reversed(range(maxup,maxdown+1)):                    solution.append(matrix[i][maxleft])                maxleft+=1            if maxup>maxdown or maxleft>maxright:                return solution            direction=(direction+1)%4        #return solution        


0 0