DAY23:leetcode #59 Spiral Matrix II

来源:互联网 发布:php爬取网页图片实例 编辑:程序博客网 时间:2024/05/05 20:21

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

Subscribe to see which companies asked this question

class Solution(object):    def generateMatrix(self, n):        """        :type n: int        :rtype: List[List[int]]        """        self.result = []        for i in range(n):            self.result.append([0]*n)        self.handleMatrix(0,1,n)        return self.result    def handleMatrix(self, start,startnum,n):        if startnum > n**2:            return        for j in range(start, n-start):            self.result[start][j] = startnum            startnum += 1        for i in range(start + 1, n-start):            self.result[i][n - start - 1] = startnum            startnum += 1        for j in range(start, n - start - 1)[::-1]:            self.result[n-start-1][j] = startnum            startnum += 1        for i in range(start + 1, n - start - 1)[::-1]:            self.result[i][start] = startnum            startnum += 1        self.handleMatrix(start + 1,startnum,n)

思路基本与54类似,不再赘述

0 0