Python solution with 4 bounds


  • 0
    class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of integers
    def spiralOrder(self, matrix):
        if not matrix:
            return []
        ans = []
        t = 0
        b = len(matrix)-1
        l = 0
        r = len(matrix[0])-1
        while t < b and l < r:
            for i in xrange(l,r):
                ans.append(matrix[t][i])
            for i in xrange(t,b):
                ans.append(matrix[i][r])
            for i in xrange(r,l,-1):
                ans.append(matrix[b][i])
            for i in xrange(b,t,-1):
                ans.append(matrix[i][l])
            t += 1
            b -= 1
            l += 1
            r -= 1
        if l == r and t ==b:
            ans.append(matrix[l][r])
        if l==r and t < b :
            for i in xrange(t,b+1):
                ans.append(matrix[i][l])
        if t == b and r > l:
            for i in xrange(l,r+1):
                ans.append(matrix[t][i])
        return ans

Log in to reply
 

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