-
Notifications
You must be signed in to change notification settings - Fork 21
/
SpiralMatrixII.py
executable file
路75 lines (65 loc) 路 1.63 KB
/
SpiralMatrixII.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# -*- coding: UTF-8 -*-
#
# 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 ]
# ]
#
# Python, Python 3 all accepted.
class SpiralMatrixII:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 0:
return []
if n == 1:
return [[1]]
matrix = [[0 for x in range(n)] for x in range(n)]
if n % 2 == 0:
center = (n - 1) // 2
else:
center = n // 2
i = 0
j = 0
depth = 0
result = 1
while i <= center and j <= center and depth <= center:
j = depth
i = depth
while j < n - depth:
if matrix[i][j] == 0:
matrix[i][j] = result
result += 1
j += 1
j -= 1
i += 1
while i < n - depth:
if matrix[i][j] == 0:
matrix[i][j] = result
result += 1
i += 1
i -= 1
j -= 1
while j >= depth:
if matrix[i][j] == 0:
matrix[i][j] = result
result += 1
j -= 1
j += 1
i -= 1
while i > depth:
if matrix[i][j] == 0:
matrix[i][j] = result
result += 1
i -= 1
depth += 1
return matrix