Question: https://oj.leetcode.com/problems/spiral-matrix-ii/
Question Name: Spiral Matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Solution: # @return a list of lists of integer def generateMatrix(self, n): if n == 0: return [] result = [[0]*n for _ in xrange(n)] current = 1 for layer in xrange(n//2): # Fill the top line for i in xrange(layer, n-layer-1): result[layer][i] = current current += 1 # Fill the right line for i in xrange(layer,n-layer-1): result[i][n-layer-1] = current current += 1 # Fill the bottom line for i in xrange(n-layer-1,layer,-1): result[n-layer-1][i] = current current += 1 # Fill the left line for i in xrange(n-layer-1,layer,-1): result[i][layer] = current current += 1 # Fill the center if n % 2 == 1: result[n//2][n//2] = current return result |