python--lintcode381.螺旋矩阵ii

描述

给你一个数n生成一个包含1-n^2的螺旋形矩阵

您在真实的面试中是否遇到过这个题?  是

样例

n = 3
矩阵为

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

这一题不是很难,四个边界值,left、right、top、bottom理清楚关系就行了。

代码如下:

class Solution:
    """
    @param n: An integer
    @return: a square matrix
    """
    def generateMatrix(self, n):
        # write your code here
        num=n*n
        count=1
        left,top=0,0
        right,bottom=n,n
        matrix=[[0 for i in range(n)] for j in range(n)]
        while(count<=num):
            for i in range(left,right):
                matrix[top][i]=count
                count+=1
            top+=1

            for i in range(top,bottom):
                matrix[i][right-1]=count
                count+=1
            right-=1

            for i in range(right-1,left-1,-1):
                matrix[bottom-1][i]=count
                count+=1
            bottom-=1

            for i in range(bottom-1,top-1,-1):
                matrix[i][left]=count
                count+=1
            left+=1
        return matrix







s = Solution()
result=s.generateMatrix(0)
for i in range(len(result)):
    print(result[i])

 

你可能感兴趣的:(python,python,算法,lintcode,leetcode)