Skip to content

Commit 4016fd3

Browse files
committed
change from recursive to iterative, change params
1 parent 4ce9afe commit 4016fd3

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

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

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
the image by 90 degrees. Can you do this in place?
66
"""
77
import unittest
8-
from typing import List, Optional
8+
from typing import List
99

1010

1111
def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
@@ -48,30 +48,21 @@ def _perform_full_rotation(matrix: List[List[int]], row: int, col: int, M: int):
4848
temp_new, matrix[rotated_row][rotated_col] = matrix[rotated_row][rotated_col], temp_new
4949

5050

51-
def rotate_matrix_in_place(
52-
matrix: List[List[int]],
53-
start_row: int = 0,
54-
start_col: int = 0,
55-
N: Optional[int] = None) -> List[List[int]]:
51+
def rotate_matrix_in_place(matrix: List[List[int]]) -> List[List[int]]:
5652
"""
5753
Does the same as rotate_matrix, but in place.
5854
Runtime: O(N^2), asymptotic runtime depends on N. We make N^2 swaps.
5955
Space Complexity: O(1), constant amount of temp variables that does not depend on N.
60-
Note: I am assuming that compiler will optimize the tail recursion.
6156
:param matrix: an NxN matrix
62-
:param start_row: starting row index
63-
:param start_col: starting col index
64-
:param N: the size of the matrix (NxN)
6557
:return: the input matrix, but rotated
6658
"""
67-
68-
if N is None:
69-
N = len(matrix)
70-
if N == 0 or N == 1:
71-
return matrix
72-
for col in range(start_col, N - 1 + start_col):
73-
_perform_full_rotation(matrix, start_row, col, N)
74-
return rotate_matrix_in_place(matrix, start_row + 1, start_col + 1, N - 2)
59+
start_row = 0
60+
N = len(matrix)
61+
for n in range(N, 1, -2):
62+
for col in range(start_row, n - 1 + start_row):
63+
_perform_full_rotation(matrix, start_row, col, n)
64+
start_row += 1
65+
return matrix
7566

7667

7768
class TestRotateMatrixFunction(unittest.TestCase):

0 commit comments

Comments
 (0)