Easy to understand solution using stack


  • 0
    C
    def spiralOrder(self, matrix):
            res = []
            if len(matrix) == 0:
                return res
            x1 = y1 = 0
            y2 = len(matrix[0]) - 1
            x2 = len(matrix) - 1
            while(x1 <= x2 and y1 <= y2):
                stack = []
                for i in range(x1, x2 + 1):
                    for j in range(y1, y2 + 1):
                        if i == x1 or i == x2 or j == y1 or j == y2:
                            if i == x1 or j == y2 and i < x2:
                                res.append(matrix[i][j])
                            else:
                                stack.insert(0,matrix[i][j])
                for i in range(len(stack)):
                    res.append(stack[i])
                x1 += 1
                y1 += 1
                y2 -= 1
                x2 -= 1
            return res

Log in to reply
 

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