@@ -28,6 +28,15 @@ def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
28
28
def _perform_full_rotation (matrix : List [List [int ]], row : int , col : int , M : int ):
29
29
"""
30
30
Helper function that performs four 90 degree rotations starting at row, col.
31
+ at a particular row and column from the matrix, there will be 4 rotations.
32
+ visually, the algorithm looks like this:
33
+ [start] (4th swap with original 3rd) - - - - - - - - - - - - - - - - - - -> (1st gets swapped with start)
34
+ | |
35
+ | |
36
+ | |
37
+ | |
38
+ (3rd swap with original 2nd) < - - - - - - - - - - - - - - - - - - - - - - (2nd gets swapped with original 1st)
39
+ this results in a full rotation in-place of a particular row and col coordinate.
31
40
:param matrix: an MxM sub-matrix out of an NxN matrix
32
41
:param row: starting row
33
42
:param col: starting column
@@ -41,7 +50,7 @@ def _perform_full_rotation(matrix: List[List[int]], row: int, col: int, M: int):
41
50
temp_new = matrix [row ][col ]
42
51
for _ in range (0 , num_rotations ):
43
52
# compute new rotated indices
44
- # (start_row * 2) is an offset to account for reduced M
53
+ # (start_row * 2) is an offset to account for reduced M into sub-matrices of matrix
45
54
rotated_col , rotated_row = M - 1 - rotated_row + (start_row * 2 ), rotated_col
46
55
# store value at newly computed indices
47
56
temp_new , matrix [rotated_row ][rotated_col ] = matrix [rotated_row ][rotated_col ], temp_new
@@ -56,8 +65,15 @@ def rotate_matrix_in_place(matrix: List[List[int]]) -> List[List[int]]:
56
65
:return: the input matrix, but rotated
57
66
"""
58
67
N = len (matrix )
68
+ # outer loop will keep reducing the matrix size 'n' by 2.
69
+ # For example, a 6x6 matrix contains a 4x4 sub-matrix, we reduce
70
+ # because at first, the values on the perimeter of the matrix will
71
+ # be rotated after the inner for-loop, and we want to start rotating
72
+ # the next sub-matrix perimeter.
59
73
for start_row , n in enumerate (range (N , 1 , - 2 )):
74
+ # rotate along the current row's columns of the current sub-matrix perimeter
60
75
for col in range (start_row , n - 1 + start_row ):
76
+ # performs 4 rotations for the current sub-matrix coordinate
61
77
_perform_full_rotation (matrix , start_row , col , n )
62
78
return matrix
63
79
0 commit comments