54. Spiral Matrix

来源:互联网 发布:2017游戏鼠标推荐 知乎 编辑:程序博客网 时间:2024/06/05 04:22

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 ]]


class Solution(object):    def spiralOrder(self, matrix):        result = []        m = len(matrix)        if  m == 0:            return result        else:            n = len(matrix[0])                #print('m=',m,'n=',n)        #print('int((min(m,n)+1)/2=',int((min(m,n)+1)/2))        for i in range(int((min(m,n)+1)/2)):            #print('i=',i)            temp_i = i            temp_j = i            #print('line1------------------------------------------')            while(temp_j>=0 and temp_j<n-i):                #print(matrix[temp_i][temp_j])                result.append(matrix[temp_i][temp_j])                temp_j+=1            temp_j-=1            temp_i+=1            #print('line2------------------------------------------')            while(temp_i>=0 and temp_i<m-i):                #print(matrix[temp_i][temp_j])                result.append(matrix[temp_i][temp_j])                temp_i+=1            temp_i-=1            temp_j-=1                        #print('line3-----------temp_i=------------temp_j=-------------------',temp_i,temp_j)            while(temp_j>=i+1 and temp_i>i):                #print(matrix[temp_i][temp_j])                result.append(matrix[temp_i][temp_j])                temp_j-=1                            #print('line4-----------temp_i=------------temp_j=-------------------',temp_i,temp_j)            while(temp_i>i and temp_j >=i):                #print(matrix[temp_i][temp_j])                result.append(matrix[temp_i][temp_j])                temp_i-=1        return result 


原创粉丝点击