我是靠谱客的博主 称心香菇,这篇文章主要介绍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
                    
                


最后

以上就是称心香菇最近收集整理的关于59. Spiral Matrix II Leetcode Python的全部内容,更多相关59.内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部