python version


  • 0
    A
    import math
    
    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            if matrix == None or len(matrix) == 0:
                return []
            resList = []
            row = len(matrix)
            col = len(matrix[0])
            layer = int(math.ceil(min(row, col) / 2.0))
    
            for lay in range(layer):
                # from left to right
                for j in range(lay, col-lay):
                    resList.append(matrix[lay][j])
                # from top to bottom
                for i in range(lay+1, row-lay-1):
                    resList.append(matrix[i][col-lay-1])
                # from right to left, avoid repeat
                if lay != row-lay-1:
                    tmpL1 = range(lay, col-lay)
                    tmpL1.reverse()
                    for j in tmpL1:
                        resList.append(matrix[row-lay-1][j])
                # from bottom to top, avoid repeat
                if lay != col-lay-1:
                    tmpL2 = range(lay+1, row-lay-1)
                    tmpL2.reverse()
                    for i in tmpL2:
                        resList.append(matrix[i][lay])
            return resList
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.