-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy path168.py
72 lines (56 loc) · 1.43 KB
/
168.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
"""
Problem:
Given an N by N matrix, rotate it by 90 degrees clockwise.
For example, given the following matrix:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
you should return:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
Follow-up: What if you couldn't use any extra space?
"""
from numpy import array
from typing import List
Matrix = List[List[int]]
def rotate_matrix(matrix: Matrix) -> Matrix:
num_layers = len(matrix) // 2
max_index = len(matrix) - 1
# rotating the matrix
for layer in range(num_layers):
for index in range(layer, max_index - layer):
(
matrix[layer][index],
matrix[max_index - index][layer],
matrix[max_index - layer][max_index - index],
matrix[index][max_index - layer],
) = (
matrix[max_index - index][layer],
matrix[max_index - layer][max_index - index],
matrix[index][max_index - layer],
matrix[layer][index],
)
return matrix
if __name__ == "__main__":
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(array(matrix))
print(array(rotate_matrix(matrix)))
print()
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(array(matrix))
print(array(rotate_matrix(matrix)))
"""
SPECS:
TIME COMPLEXITY: O(n x m)
SPACE COMPLEXITY: O(1)
"""