Source of the topic
https://leetcode.com/problems/spiral-matrix-ii/
Given an integer n, generate a square matrix filled with elements from 1 to n2 in Spiral order.
Test instructions Analysis
Input:n:integer
Output:a matrix decribed as list[list[]
Conditions: Enter a size, get a square matrix, and then form a serpentine matrix
Topic ideas
The topic and 54 belong to a category, are serpentine traversal, where the direct Mr. into an initialized matrix, and then iterate over, using the cumulative variable to assign value
AC Code (PYTHON)
__author__='YE'classsolution (object):defGeneratematrix (self, n):""": Type N:int:rtype:list[list[int]]""" ifn = =0:return[] Matrix= [] forIinchrange (N): l= [0 forJinchrange (n)] Matrix.append (l) up=0 Left=0 Down= Len (Matrix)-1 Right= Len (matrix[0])-1Direct=0 Res=[] Count= 1 whileTrue:ifDirect = =0: forIinchRange (left, right + 1): Matrix[up][i]=Count Count+ = 1 up+ = 1ifDirect = = 1: forIinchRange (up, down + 1): Matrix[i][right]=Count Count+ = 1 Right-= 1ifDirect = = 2: forIinchRange (right, left-1, 1): Matrix[down][i]=Count Count+ = 1 Down-= 1ifDirect = = 3: forIinchRange (down, up-1, 1): Matrix[i][left]=Count Count+ = 1 Left+ = 1ifUp > DownorLeft >Right :returnMatrix Direct= (direct + 1)% 4Print(Solution (). Generatematrix (3))
[Leetcode] (python): 059-spiral Matrix II