Easy to understand python solution


  • 0
    F

    Just append the number from outside to inside, if the outside is m by n, then we append row matrix[0][0] to matrix[0][n-2], column matrix[0][n-1] to matrix[0][m-2], row matrix[m-1][n-1] to matrix[m-1][1], and column matrix[m-1][0] to matrix[1][0].
    After min(length, width)/2 loop, there might be a column or row left. So we need to check it and append those cells into the array. Also note that we need to add an equal sign to one of these two conditions since there might be a single cell left in the middle.

    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            if not matrix or not matrix[0]:
                return []
            m, n = len(matrix), len(matrix[0])
            level = 0
            result = []
            for i in xrange(min(m, n)/2):
                for j in xrange(level, n-level-1):
                    result.append(matrix[level][j])
                for j in xrange(level, m-level-1):
                    result.append(matrix[j][n-level-1])
                for j in xrange(n-1-level, level, -1):
                    result.append(matrix[m-level-1][j])
                for j in xrange(m-1-level, level, -1):
                    result.append(matrix[j][level])
                level += 1
            if n >= m and m%2 == 1:
                for j in xrange(level, n-level):
                    result.append(matrix[level][j])
            elif m > n and n%2 == 1:
                for j in xrange(level, m-level):
                    result.append(matrix[j][level])
            return result
    

Log in to reply
 

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