[LeetCode]54. Spiral Matrix

54. Spiral Matrix

題意:螺旋打印二維矩陣html

1. 正常作法

直接按照螺旋的思想一個個打印出來。python

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. 數組彈出

思想和上面螺旋的思想是一致的,不同的是其用的是數組的彈出的作法來獲取元素,可是這有個缺點-數組的彈出可能會致使運行時間的增長。web

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])
相關文章
相關標籤/搜索