【LEETCODE】59-Spiral Matrix II

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 ]

]


题意:

给一个整数 n,生成一个方阵,由 1 到 n^2 的螺旋顺序构成


参考:

http://www.cnblogs.com/zuoyuan/p/3769892.html


思路:

用count去在该有的位置填入该有的数字,当count满足n*n时则返回最终结果

用 up right down left 分别去当四条边的指针,填满一条边后进行更新

direct 是除4的余数,用来控制目前应该填入哪条边了




class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n==0:
            return []
        
        matrix=[[n for i in range(n)]for j in range(n)]
        
        left=0
        up=0
        right=n-1
        down=n-1
        
        direct=0
        count=0
        
        while True:
            if direct==0:                           #此时为 上边
                for i in range(left,right+1):       #up控制上边 当前的行,left为当前起点,right为终点
                    count+=1
                    matrix[up][i]=count
                up+=1                               #写完一行,要进行更新
                
            if direct==1:                           #右边
                for i in range(up,down+1):
                    count+=1
                    matrix[i][right]=count
                right-=1
                
            if direct==2:                           #下边
                for i in range(right,left-1,-1):
                    count+=1
                    matrix[down][i]=count
                down-=1
                
            if direct==3:                           #左边
                for i in range(down,up-1,-1):
                    count+=1
                    matrix[i][left]=count
                left+=1
                
            if count==n*n:                          #终止条件
                return matrix
                
            direct=(direct+1)%4                     #更新边的方向


你可能感兴趣的:(LeetCode,python)