59. Spiral Matrix II Leetcode Python

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.


For example,
Given n = 3,


You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]

]

这题的解法和spiral matrix1的解法一样,不同的是这个问题的行和列数都一样,所以在算的时候稍微简单一些。

代码如下:

class Solution:
    # @return a list of lists of integer
    def generateMatrix(self, n):
        maxup=0
        maxleft=0
        maxright=n-1
        maxdown=n-1
        direction=0
        matrix=[[0 for i in range(n)] for j in range(n)]
        num=range(1,n*n+1)
        iter=0
        while True:
            if direction==0:
                for i in range(maxleft,maxright+1):
                    matrix[maxup][i]=num[iter]
                    iter+=1
                maxup+=1
            if direction==1:
                for i in range(maxup,maxdown+1):
                    matrix[i][maxright]=num[iter]
                    iter+=1
                maxright-=1
            if direction==2:
                for i in reversed(range(maxleft,maxright+1)):
                    matrix[maxdown][i]=num[iter]
                    iter+=1
                maxdown-=1
            if direction==3:
                for i in reversed(range(maxup,maxdown+1)):
                    matrix[i][maxleft]=num[iter]
                    iter+=1
                maxleft+=1
            if maxleft>maxright or maxup>maxdown:
                return matrix
            direction=(direction+1)%4
                    
                


你可能感兴趣的:(leetcode)