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

解题方法

和1类似,将数字一个个填进去

Solution

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 0:
            return []
        result = [[0 for i in range(n)] for j in range(n)]
        self.helper(result, 1, 0, 0, n-1, n-1)
        return result

    def helper(self, result, num, startX, startY, endX, endY):
        if startX == endX:
            for i in range(startY, endY + 1):
                result[startX][i] = num
                num += 1
            return
        if startY == endY:
            for i in range(startX, endX + 1):
                result[i][startY] = num
                num += 1
            return

        # upper row
        for i in range(startY, endY):
            result[startX][i] = num
            num += 1

        # right column
        for i in range(startX, endX):
            result[i][endY] = num
            num += 1

        # bottom row
        for i in range(endY, startY, -1):
            result[endX][i] = num
            num += 1

        # left column
        for i in range(endX, startX, -1):
            result[i][startY] = num
            num += 1

        sX = startX + 1
        sY = startY + 1
        eX = endX - 1
        eY = endY - 1
        if eX >= sX and eY >= sY:
            self.helper(result, num, sX, sY, eX, eY)

Reference