59. Spiral Matrix II

给定一个正整数向一个n*n的矩阵中一次按照顺时针螺旋顺序放入1-n^2的数字:

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
class Solution:
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if not n:
            return []
        result = [[0 for _ in range(n)] for _ in range(n)]
        left, right, up, down = 0, n-1, 0, n-1
        k=1
        while(left<=right and up<=down):
            for i in range(left, right+1):
                result[up][i] = k
                k += 1
            up += 1
            if left>right or up>down:
                break
            for i in range(up, down+1):
                result[i][right] = k
                k += 1
            right -= 1
            if left>right or up>down:
                break
            for i in range(right, left-1, -1):
                result[down][i] = k
                k += 1
            down -= 1
            if left>right or up>down:
                break
            for i in range(down, up-1, -1):
                result[i][left] = k
                k += 1
            left += 1
        return result

 


想到的方法:1,事先根据坐标算出该坐标数值

2,按照题目方法顺时针挨个放入即可

我用的方法二:

 

posted @ 2018-12-24 15:50  茫茫碧落  阅读(135)  评论(0编辑  收藏  举报