Python solution with detailed explanation

  • 0


    Spiral Matrix

    1. The idea is simple. Maintain four variables rs,re,cs,ce. Use these four to peel off the outer layer of the matrix described by those four parameters. Then update those four parameters until you hit boundary conditions.
    2. The devil lies in the following:
    • Be very careful with for loops printing rows and columns. Pay special attention to rs,re,cs,ce.
    • Be very careful with edge cases like [], [[1,2,3]], [[1],[2],[3]] i.e empty matrix, single row matrix, and single column matrix.
    class Solution(object):
        def outer_layer(self, matrix, rs, re, cs, ce, result):
            for j in range(cs, ce+1):
            if rs == re:
            for i in range(rs+1, re+1):
            if cs == ce:
            for j in range(ce-1, cs-1, -1):
            for i in range(re-1, rs, -1):
        def spiralOrder(self, matrix):
            :type matrix: List[List[int]]
            :rtype: List[int]
            if matrix == []:
                return []
            M, N = len(matrix), len(matrix[0])
            rs, re, cs, ce = 0, M-1, 0, N-1
            result = []
            while rs <= re and cs <= ce:
                self.outer_layer(matrix, rs, re, cs, ce, result)
                rs, re = rs+1, re-1
                cs, ce = cs+1,ce-1
            return result        

    Another interesting problem:

Log in to reply

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