An iterative Python solution using 36ms


  • 0
    Z
    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            
            if not matrix:
                return []
            
            res = []
            
            m = len(matrix)
            n = len(matrix[0])
            
            j = 0
            
            if min(m, n) % 2 == 0:
                end = min(m, n) / 2
            else:
                end = min(m, n) / 2 + 1
            
            while j < end:
                for i in xrange(j, n-j):
                    res.append(matrix[j][i])
                    
                if m-1-j == j:
                    break
            
                for i in xrange(1+j, m-j):
                    res.append(matrix[i][n-j-1])
                    
                if n-1-j == j:
                    break
                
                for i in xrange(1+j, n-j):
                    res.append(matrix[m-1-j][n-i-1])
                
                for i in xrange(1+j, m-1-j):
                    res.append(matrix[m-i-1][j])
                    
                j += 1
                    
            return res

Log in to reply
 

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