classSolution(object):defgenerateMatrix(self,n):""" :type n: int :rtype: List[List[int]] """ifn==0:return[]ifn==1:return[[1]]ret=[[0]*nforiinrange(n)]direct=0# 0: go right, 1: go down, 2: go left, 3: got upl=0r=n-1u=0d=n-1num=1whilel<=dandu<=d:ifdirect==0:foriinrange(l,r+1):ret[u][i]=numnum+=1u+=1direct=1elifdirect==1:foriinrange(u,d+1):ret[i][r]=numnum+=1r-=1direct=2elifdirect==2:foriinrange(r,l-1,-1):ret[d][i]=numnum+=1d-=1direct=3else:# direct == 3foriinrange(d,u-1,-1):ret[i][l]=numnum+=1l+=1direct=0returnret