Python solution using complex numbers as vectors


  • 0
    M

    Pass through the array by using a vector with gets multiplied by 1j each time it reaches the boundary.
    The complex indices of a 3x3 will look like this:

    [[0, 1, 2],
    [ j, j+1, j+2],
    [2j, 2j+1, 2j+2]]

    class Solution(object):
        def spiralOrder(self, matrix):
            if not matrix:
                return []
            ans = []
            v, pos = 1, -1 + 0j
            bound = len(matrix[0]) + (len(matrix)-1)*1j
            while bound.real > 0:
                for i in range(int(bound.real)):
                    pos = pos + v
                    ans.append(matrix[int(pos.imag)][int(pos.real)])
                bound = (bound - 1) * 1j
                bound = abs(bound.real) + bound.imag*1j
                v *= 1j
            return ans
    

    I'm hoping someone will have an idea on how to clean up the use of the 'bound' variable.


Log in to reply
 

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