LC 54 Spiral matrix

    def spiralOrder(self, matrix: 'List[List[int]]') -> 'List[int]':
        if not matrix:
        res = []
        r1, r2 = 0, len(matrix) - 1
        c1, c2 = 0, len(matrix[0]) - 1

        while  r1 <= r2 and c1 <= c2:
            for i in range(c1, c2 + 1):
            for i in range(r1 + 1, r2 + 1):

            if r1 < r2 and c1 < c2:
                for i in range(c2 - 1, c1 , -1):
                for i in range(r2, r1, -1):

            r1 += 1; r2 -= 1
            c1 += 1; c2 -= 1
        return res

c1, c2, r1, r2 defines a matrix. Each iteration of the while loop will peel off the outmost layer of the matrix.

Corner cases

1 dim matrix

The if statement in while is used to deal with the fact in such case. since r1 = r2, we don’t need to collect entry vertically. We also have collected horizontally in the first for loop, so we can jump through the second horizontal for loop.

The same with vertical 1 dim matrix.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see