classSolution(object):defgenerateMatrix(self,n):""" :type n: int :rtype: List[List[int]] """begin=0nn=n*nnums=[]foriinrange(nn,0,-1):nums.append(i)# create a num list to usematrix=[[0forxinrange(n)]foryinrange(n)]# create an empty matrix. Attention! Don't use [[0]*n]*n!ifn==0:return[]else:returnself.rotate(matrix,begin,n-1,nums)#-------|#| |defrotate(self,cube,start,end,numslist):# traversal each peering #|-------|# base stateifstart<=end:# don't forget this condition!ifstart==end:# if the central is remaincube[start][start]=numslist.pop()else:foryinrange(start,end+1):# if last row, traversal the columncube[start][y]=numslist.pop()forxinrange(start+1,end+1):# if 2nd column, traversal the rowcube[x][end]=numslist.pop()foryinrange(end-1,start-1,-1):# if 3rd row, traversal the columncube[end][y]=numslist.pop()forxinrange(end-1,start+1-1,-1):# if 4th column, traversal the rowcube[x][start]=numslist.pop()self.rotate(cube,start+1,end-1,numslist)# peering next inside layerreturncubeif__name__=="__main__":answer=Solution()printanswer.generateMatrix(3)
近期评论