1
+ '''Question:
2
+ Given an image represented by an NxN matrix, where each pixel in the image is
3
+ 4 bytes, write a method to rotate the image by 90 degrees.
4
+
5
+ Can you do this in place?
6
+
7
+ clarifications:
8
+ - assume rotate closewise
9
+ - input: matrix
10
+ - return: None
11
+ '''
12
+
13
+ from math import ceil
14
+ import copy
15
+ import unittest
16
+ from test_utils import UnitTestBase
17
+
18
+ # Solution:
19
+ # Hint: draw a 4x4 matrix as an example
20
+ # Time: O(N*N)
21
+ # Space: O(1)
22
+ # Hotspot: if N is odd, it will be wrong to use range(ceil(n/2)) to loop i.
23
+ # The reason is it will end up rotating twice for some cells
24
+ def rotate_matrix (matrix ):
25
+ n = len (matrix )
26
+ for i in range (n // 2 ):
27
+ for j in range (ceil (n / 2 )):
28
+ tmp = matrix [i ][j ]
29
+ matrix [i ][j ] = matrix [n - 1 - j ][i ]
30
+ matrix [n - 1 - j ][i ] = matrix [n - 1 - i ][n - 1 - j ]
31
+ matrix [n - 1 - i ][n - 1 - j ] = matrix [j ][n - 1 - i ]
32
+ matrix [j ][n - 1 - i ] = tmp
33
+
34
+ class TestStrComp (UnitTestBase , unittest .TestCase ):
35
+ def data_provider (self ):
36
+ return [
37
+ ([], []),
38
+ ([['1111' ]], [['1111' ]]),
39
+ ([['1111' ,'2222' ], ['3333' ,'4444' ]], [['3333' ,'1111' ], ['4444' ,'2222' ]]),
40
+ ([['1111' ,'2222' ,'3333' ], ['4444' ,'5555' ,'6666' ], ['7777' ,'8888' ,'9999' ]],
41
+ [['7777' ,'4444' ,'1111' ], ['8888' ,'5555' ,'2222' ], ['9999' ,'6666' ,'3333' ]],
42
+ ),
43
+ ([['1111' ,'2222' ,'3333' , '4444' ],
44
+ ['5555' ,'6666' ,'7777' , '8888' ],
45
+ ['9999' ,'0000' ,'aaaa' , 'bbbb' ],
46
+ ['cccc' ,'dddd' ,'eeee' , 'ffff' ]],
47
+ [['cccc' ,'9999' ,'5555' , '1111' ],
48
+ ['dddd' ,'0000' ,'6666' , '2222' ],
49
+ ['eeee' ,'aaaa' ,'7777' , '3333' ],
50
+ ['ffff' ,'bbbb' ,'8888' , '4444' ]],
51
+ ),
52
+ ]
53
+
54
+ def func_provider (self ):
55
+ return [
56
+ rotate_matrix ,
57
+ ]
58
+
59
+ def single_test (self , func , data ):
60
+ cpy = copy .deepcopy (data )
61
+ matrix = data [0 ]
62
+ func (matrix )
63
+ self .expect (matrix , func , cpy )
64
+
65
+ if __name__ == '__main__' :
66
+ unittest .main ()
0 commit comments