题目来源:
https://leetcode.com/problems/spiral-matrix-ii/
题意分析:
给定一个整型n,将1到n²按照螺旋规律输入一个n×n的矩阵里面。
题目思路:
和前面一道螺旋矩阵类似。先初始化一个n×n矩阵。按照螺旋规律访问这个矩阵并填数。
代码(python):
class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ ans = [[0 for i in range(n)] for j in range(n)] r,l,size,m,count = 0,0,n - 1,n - 1,1 while r <= m and l <= size: for i in range(r,m+1): ans[l][i] = count;count += 1 l += 1 for i in range(l,size + 1): ans[i][m] = count;count += 1 m -= 1;i = m while i >= r: ans[size][i] = count;count += 1; i -= 1 size -= 1; i = size while i >= l: ans[i][r] = count; count += 1;i -= 1 r += 1 return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4988208.html