Skip to content

Latest commit

 

History

History
65 lines (55 loc) · 1.41 KB

059.md

File metadata and controls

65 lines (55 loc) · 1.41 KB

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 ]
]

思路:

解法1:生成一个二维数组,使用4个值up,down,left,right限制是个方向,4个循环按照螺旋的规则初始化二维数组,知道全部填满。(cnt=n^2的时候)

代码:

解法1

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        result = [[0 for i in range(n)] for i in range(n)]
        d,u,l,r = n,-1,-1,n
        cnt = 0
        n2 = n*n
        while cnt != n2:
            for j in range(l+1, r):
                cnt += 1
                result[u+1][j] = cnt
            if cnt == n2:
                break
            u += 1
            for i in range(u+1, d):
                cnt += 1
                result[i][r-1] = cnt
            r -= 1
            if cnt == n2:
                break
            for j in range(r-1, l,-1):
                cnt += 1
                result[d-1][j] = cnt
            d -= 1
            if cnt == n2:
                break
            for i in range(d-1, u, -1):
                cnt += 1
                result[i][l+1] = cnt
            l += 1
            if cnt == n2:
                break;
        return result