54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example, Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Solution:

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return []

        vals = []
        up, down = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1
        while up <= down and left <= right:

            for col in xrange(left, right + 1):
                vals.append(matrix[up][col])
            up += 1
            if up > down:
                break

            for row in xrange(up, down + 1):
                vals.append(matrix[row][right])
            right -= 1
            if right < left:
                break

            for col in xrange(right, left - 1, -1):
                vals.append(matrix[down][col])
            down -= 1
            if down < up:
                break

            for row in xrange(down, up - 1, -1):
                vals.append(matrix[row][left])
            left += 1
            if left > right:
                break

        return vals

results matching ""

    No results matching ""