@@ -25,6 +25,33 @@ def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
25
25
return rotated
26
26
27
27
28
+ def perform_full_rotation (matrix : List [List [int ]], row : int , col : int , N : Optional [int ] = None ):
29
+ """
30
+ Helper function that performs four 90 degree rotations starting at row, col.
31
+ :param matrix: an NxN matrix
32
+ :param row: starting row
33
+ :param col: starting column
34
+ :param N: size of matrix
35
+ :return:
36
+ """
37
+ if N is None :
38
+ N = len (matrix )
39
+ num_rotations = 4
40
+ start_row = row
41
+ rotated_row = row
42
+ rotated_col = col
43
+ temp_new = matrix [row ][col ]
44
+ for r in range (0 , num_rotations ):
45
+ temp = temp_new
46
+ # compute new rotated indices
47
+ prev_col = rotated_col
48
+ rotated_col = N - 1 - rotated_row + (start_row * 2 ) # offset to account for reduced N
49
+ rotated_row = prev_col
50
+ # store value at newly computed indices
51
+ temp_new = matrix [rotated_row ][rotated_col ]
52
+ matrix [rotated_row ][rotated_col ] = temp
53
+
54
+
28
55
def rotate_matrix_in_place (
29
56
matrix : List [List [int ]],
30
57
start_row : int = 0 ,
@@ -44,22 +71,10 @@ def rotate_matrix_in_place(
44
71
45
72
if N is None :
46
73
N = len (matrix )
47
- num_rotations = 4
48
74
if N == 0 or N == 1 :
49
75
return matrix
50
76
for col in range (start_col , N - 1 + start_col ):
51
- rotated_row = start_row
52
- rotated_col = col
53
- temp_new = matrix [start_row ][col ]
54
- for r in range (0 , num_rotations ):
55
- temp = temp_new
56
- # compute new rotated indices
57
- prev_col = rotated_col
58
- rotated_col = N - 1 - rotated_row + (start_row * 2 ) # offset to account for reduced N
59
- rotated_row = prev_col
60
- # store value at newly computed indices
61
- temp_new = matrix [rotated_row ][rotated_col ]
62
- matrix [rotated_row ][rotated_col ] = temp
77
+ perform_full_rotation (matrix , start_row , col , N )
63
78
return rotate_matrix_in_place (matrix , start_row + 1 , start_col + 1 , N - 2 )
64
79
65
80
0 commit comments