Skip to content

Commit 036a3c3

Browse files
committed
add comments for in-place matrix rotate
1 parent 5c34387 commit 036a3c3

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

Python/chapter01/1.7 - Rotate Matrix/miguel_1.7_sol.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
2828
def _perform_full_rotation(matrix: List[List[int]], row: int, col: int, M: int):
2929
"""
3030
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.
3140
:param matrix: an MxM sub-matrix out of an NxN matrix
3241
:param row: starting row
3342
:param col: starting column
@@ -41,7 +50,7 @@ def _perform_full_rotation(matrix: List[List[int]], row: int, col: int, M: int):
4150
temp_new = matrix[row][col]
4251
for _ in range(0, num_rotations):
4352
# 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
4554
rotated_col, rotated_row = M - 1 - rotated_row + (start_row * 2), rotated_col
4655
# store value at newly computed indices
4756
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]]:
5665
:return: the input matrix, but rotated
5766
"""
5867
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.
5973
for start_row, n in enumerate(range(N, 1, -2)):
74+
# rotate along the current row's columns of the current sub-matrix perimeter
6075
for col in range(start_row, n - 1 + start_row):
76+
# performs 4 rotations for the current sub-matrix coordinate
6177
_perform_full_rotation(matrix, start_row, col, n)
6278
return matrix
6379

0 commit comments

Comments
 (0)