- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSpiralMatrix.py
More file actions
Latest commit
79 lines (65 loc) · 1.49 KB
/
Copy pathSpiralMatrix.py
File metadata and controls
79 lines (65 loc) · 1.49 KB
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
76
77
78
79
'''
Given an integer n,
generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
'''
defspiral_matrix(n):
# create the empty matrix
matrix= [[None]*nforiinrange(n)]
# starting position (x,y)
x,y=0,0
# the direction of the increment of x and y
dx,dy=1,0
forjinrange(n**2):
matrix[y][x] =j+1
nx,ny=x+dx, y+dy
if0<=nx<nand0<=ny<nandmatrix[ny][nx] ==None:
x,y=nx,ny
else:
# changing the direction of x and y
# magic part!!!!
dx,dy=-dy,dx
x,y=x+dx,y+dy
returnmatrix
matrix=spiral_matrix(3)
forrowinmatrix:
printrow
'''
Given a matrix of m x n elements (m rows, n columns),
return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
defspiral_matrix2(matrix,m,n):
nums= []
x_bounds= [0, m]
y_bounds= [0, n]
sx,sy=0,0
dx,dy=1,0
for_inrange(m*n):
nums.append(matrix[sy][sx])
nx,ny=sx+dx, sy+dy
ifx_bounds[0] <=nx<x_bounds[1] andy_bounds[0] <=ny<y_bounds[1]:
sx,sy=nx,ny
else:
dx,dy=-dy,dx
sx,sy=sx+dx, sy+dy
returnnums
matrix= [[1,2,3],[4,5,6],[7,8,9]]
printspiral_matrix2(matrix,3,3)
'''
given you a list of number, print the matrix in spiral order
'''