[LeetCode]54. Spiral Matrix

54. Spiral Matrix

题意:螺旋打印二维矩阵

1. 正常做法

直接按照螺旋的思想一个个打印出来。

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return matrix
        start_row, end_row = 0, len(matrix) - 1
        start_col, end_col = 0, len(matrix[0]) - 1
        ans = []
        while start_row <= end_row and start_col <= end_col:
            # 向右移动
            for j in range(start_col, end_col+1):
                ans.append(matrix[start_row][j])
            start_row += 1
            # 向下移动
            for i in range(start_row, end_row+1):
                ans.append(matrix[i][end_col])
            end_col -= 1
            # 向左移动
            if start_row <= end_row:
                for j in range(end_col, start_col-1, -1):
                    ans.append(matrix[end_row][j])
            end_row -= 1
            # 向上移动
            if start_col <= end_col:
                for i in range(end_row, start_row-1, -1):
                    ans.append(matrix[i][start_col])
            start_col += 1
        return ans

2. 数组弹出

思想和上面螺旋的思想是一致的,不一样的是其用的是数组的弹出的做法来获取元素,但是这有个缺点-数组的弹出可能会导致运行时间的增加。

def spiralOrder(self, matrix):
    ret = []
    while matrix:
        # 弹出上面
        ret += matrix.pop(0)
        # 弹出右边
        if matrix and matrix[0]:
            for row in matrix:
                ret.append(row.pop())
        # 弹出下面
        if matrix:
            ret += matrix.pop()[::-1]
        # 弹出左边
        if matrix and matrix[0]:
            for row in matrix[::-1]:
                ret.append(row.pop(0))
    return ret

3. 递归

这种写法非常Pythonic,但是在大的的数组中会非常的耗时,其思想就是每次递归时取第一个子数组,将剩余的子数组进行zip,反转得到的数组再进行递归。

class Solution(object):
    def spiralOrder(self, matrix):
        return matrix and list(matrix.pop(0)) + spiralOrder(list(zip(*matrix))[::-1])
posted @ 2017-08-20 01:03  banananana  阅读(200)  评论(0编辑  收藏  举报