Python - edge by edge - no matrix modification - 38ms


  • 0
    A
    class Solution(object):
        def spiralOrder(self, a):
            output = []
            if a:
                h, w = len(a), len(a[0])
                curr = i = 0
                needed = min(h,w) # needed number of passes in the loop
                while curr < needed:
                    output += a[i][i:w-i] + [x[w-i-1] for x in a[i+1:h-i]] # adding top and right edges
                    curr += 1
                    if curr < needed:  
                        output += a[-1-i][i:w-1-i][::-1] + [x[0+i] for x in a[1+i:h-1-i][::-1]] # adding bottom and left edges
                        curr += 1
                    i += 1
    
            return output
    

Log in to reply
 

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