Skip to content

Commit f7c3679

Browse files
committed
helper function to make rotate in place cleaner
1 parent 4249957 commit f7c3679

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

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

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,33 @@ def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
2525
return rotated
2626

2727

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+
2855
def rotate_matrix_in_place(
2956
matrix: List[List[int]],
3057
start_row: int = 0,
@@ -44,22 +71,10 @@ def rotate_matrix_in_place(
4471

4572
if N is None:
4673
N = len(matrix)
47-
num_rotations = 4
4874
if N == 0 or N == 1:
4975
return matrix
5076
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)
6378
return rotate_matrix_in_place(matrix, start_row + 1, start_col + 1, N - 2)
6479

6580

0 commit comments

Comments
 (0)