Sharing my Python recursive solution, useful to see Python slicing + list comprehension


  • 0
    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            def print_matrix(matrix, start_row, start_col, end_row, end_col, ret_list):
                if start_col > end_col or start_row > end_row: 
                    return
                first_row  = matrix[start_row][start_col:end_col + 1]
                first_col  = [matrix[row][end_col] for row in range(start_row + 1, end_row + 1)]
                second_row = matrix[end_row][start_col:end_col][::-1] if start_row != end_row else []
                second_col = [matrix[row][start_col] for row in range(start_row + 1, end_row)][::-1] if start_col != end_col else []
                ret_list += first_row + first_col + second_row + second_col
                print_matrix(matrix, start_row + 1, start_col + 1, end_row - 1, end_col -1, ret_list)
            
            ret_list = []
            if len(matrix) != 0:
                print_matrix(matrix, 0, 0, len(matrix) - 1, len(matrix[0]) - 1, ret_list)
            return ret_list

Log in to reply
 

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