Thursday, September 18, 2014

Leetcode: Spiral Matrix @Python

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of integers
    def spiralOrder(self, matrix):
        rst=[]
        m=len(matrix)
        if m>0:
            n=len(matrix[0])
        else:
            return rst
        up=0
        down=m-1
        left=0
        right=n-1
        while up<=down and left<=right:
            rst.extend(matrix[up][left:right+1])
            up+=1
            if up<=down:
                for i in range(up,down+1): rst.append(matrix[i][right])
                right-=1
            else:
                break
            if left<=right:
                for i in reversed(range(left,right+1)): rst.append(matrix[down][i])
                down-=1
            else:
                break
            if down>=up:
                for i in reversed(range(up,down+1)): rst.append(matrix[i][left])
                left+=1
            else:
                break
        return rst

No comments :

Post a Comment