【leetcode - 54】螺旋矩阵 medium

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:

输入:
[
[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: List[List[int]]) -> List[int]:
        if not matrix:
            return matrix
        rownum = len(matrix)
        colnum = len(matrix[0])
        #记录是否到达循环
        indexnum = 0
        #设置方向向量 右下左上
        row = [0,1,0,-1]
        col = [1,0,-1,0]
        #记录是否遍历过这个元素位置
        mm = []
        #开始遍历
        x,y = 0,0
        res = []
        for i in range(rownum*colnum):
            res.append(matrix[x][y])
            mm.append((x,y))
            new_x = x+row[indexnum]
            new_y = y+col[indexnum]
            if 0<=new_x<rownum and 0<=new_y<colnum and (new_x,new_y) not in mm:
                x,y = new_x,new_y
            else:
                indexnum = (indexnum+1)%4
                x,y = x+row[indexnum],y+col[indexnum]
        return res

 

posted @ 2020-10-20 20:19  Akassy  阅读(65)  评论(0)    收藏  举报