LeetCode Spiral Matrix

LeetCode解題之Spiral Matrix


原題

將一個矩陣中的內容螺旋輸出。css

注意點:python

  • 矩陣不必定是正方形

樣例:git

輸入: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]github

輸出: [1, 2, 3, 6, 9, 8, 7, 4, 5]markdown

解題思路

控制好當前遍歷的邊界,不斷的向內縮進。app

需要注意的是,縮到最裏面的時候可能會出現下面幾種狀況:post

中心剩下一個數值
———
|3|
———

中心橫向多個數值
—————————
|3 4 5 6|
—————————

中心縱向多個數值
———
|2|
|3|
|4|
———

分別處理一下就能夠。spa

AC源代碼

class Solution(object):
    def spiralOrder(self, matrix):
        """ :type matrix: List[List[int]] :rtype: List[int] """
        if not matrix:
            return []
        left = top = 0
        right = len(matrix[0]) - 1
        bottom = len(matrix) - 1

        result = []
        while left < right and top < bottom:
            for i in range(left, right):
                result.append(matrix[top][i])
            for i in range(top, bottom):
                result.append(matrix[i][right])
            for i in range(right, left, -1):
                result.append(matrix[bottom][i])
            for i in range(bottom, top, -1):
                result.append(matrix[i][left])
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        if left == right and top == bottom:
            result.append(matrix[top][left])
        elif left == right:
            for i in range(top, bottom + 1):
                result.append(matrix[i][left])
        elif top == bottom:
            for i in range(left, right + 1):
                result.append(matrix[top][i])
        return result


if __name__ == "__main__":
    assert Solution().spiralOrder([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]) == [1, 2, 3, 6, 9, 8, 7, 4, 5]
    assert Solution().spiralOrder([[2], [3]]) == [2, 3]
    assert Solution().spiralOrder([[2, 3]]) == [2, 3]

歡迎查看個人Github (https://github.com/gavinfish/LeetCode-Python) 來得到相關源代碼。code

相關文章
相關標籤/搜索