59. Spiral Matrix II

2019-05-09

59. Spiral Matrix II

Given a positive integer _n_, generate a square matrix filled with elements from 1 to _n_2 in spiral order.

Example:

1
2
3
4
5
6
7
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Code:

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
A, lo = [], n*n+1
while lo > 1:
lo, hi = lo - len(A), lo
A = [range(lo, hi)] + zip(*A[::-1])
return A
1
2
3
||  =>  |9|  =>  |8|      |6 7|      |4 5|      |1 2 3|
|9| => |9 8| => |9 6| => |8 9 4|
|8 7| |7 6 5|
-->