【leetcode】54. 螺旋矩陣

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

輸入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]

解題思路:

class Solution:
    def spiralOrder(self, matrix):
        res = []
        row = len(matrix)
        col = len(matrix[0])
        x1,y1 = 0,0
        x2,y2 = row-1,col-1
        while x1 <= x2 and y1 <= y2:
            # print(x1,y1)
            for i in range(x1, x2+1):
                res.append(martix[y1][i])
                # print(martix[y1][i])

            for j in range(y1+1,y2+1):
                res.append(martix[j][x2])
                # print(martix[j][x2])
            # print(x2,y2)
            # print('-----')
            if x1<x2 and y1<y2:
                for i in range(x2-1,x1,-1):
                    res.append(martix[y2][i])
                    # print(martix[y2][i])
                # print('------')
                for j in range(y2,y1,-1):
                    res.append(martix[j][x1])
                    # print(martix[j][x1])

            x1 += 1
            y1 += 1
            x2 -= 1
            y2 -= 1

        return res

參考:

Leetcode 54:螺旋矩陣(最詳細的解法!!!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章