LeetCode-59-Spiral Matrix II 模拟水题

来源:互联网 发布:中银淘宝信用卡查询 编辑:程序博客网 时间:2024/05/19 03:25

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


原创粉丝点击