LeetCode-54-Spiral Matrix 模拟

来源:互联网 发布:二维码生成算法 c语言 编辑:程序博客网 时间:2024/06/03 21:57


class Solution(object):    def spiralOrder(self, matrix):        """        :type matrix: List[List[int]]        :rtype: List[int]        """        d=[[0,1],[1,0],[0,-1],[-1,0]]        Lenm=len(matrix)        if Lenm==0:return []        if Lenm==1:return matrix[0]        Lenn=len(matrix[0])        used=[[0 for x in range(Lenn)]for y in range(Lenm)]        x=0        y=0        direction=0        ans=[matrix[0][0]]        used[0][0]=1        for i in range(1,Lenm*Lenn):            while(True):                newx=x+d[direction][0]                newy=y+d[direction][1]                if newx>=0 and newx<Lenm and newy>=0 and newy<Lenn and used[newx][newy]==0:                    used[newx][newy]=1                    ans.append(matrix[newx][newy])                    x=newx                    y=newy                    break                else:                    direction=(direction+1)%4        return ans            


原创粉丝点击