[Array]59. Spiral Matrix II

  • 分类:Array
  • 时间复杂度: O(n*m)

59. Spiral Matrix II

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

代码:

方法:

class Solution:
    def generateMatrix(self, n: 'int') -> 'List[List[int]]':
        
        if n==0:
            return [[]]
        
        matrix=[[0 for i in range(n)] for i in range(n)]
        
        num=1
        top,left,row,col=0,0,0,0
        right,bottom=n-1,n-1
        
        while top<bottom and left<right:
            while col<right:
                matrix[row][col]=num
                col+=1
                num+=1
            while row<bottom:
                matrix[row][col]=num
                row+=1
                num+=1
            while col>left:
                matrix[row][col]=num
                col-=1
                num+=1
            while row>top:
                matrix[row][col]=num
                row-=1
                num+=1
            top+=1
            left+=1
            col+=1
            row+=1
            bottom-=1
            right-=1
        
        if top==bottom and left==right:
            matrix[top][left]=num
        
        return matrix

讨论:

1.谨记四个角的坐标不要写错了。。。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 不要回头 余生各自安好 好到忘了整个曾经
    嫣香落阅读 609评论 0 49
  • 每个人大概都会有周期性的情绪低落。 这件事如同自然规律,一旦这个周期开始,我们便很难去强行叫停。 不过也慢慢的,开...
    林周五阅读 240评论 0 0
  • 金蝉蜕皮以后就是知了。 在老家,金蝉是一道菜品,一般是油煎而成,再撒上孜然,就可以吃了,香脆可口,写到这我已经咽口...
    yueqianW阅读 2,197评论 0 0