|
5 | 5 | the image by 90 degrees. Can you do this in place?
|
6 | 6 | """
|
7 | 7 | import unittest
|
8 |
| -from typing import List, Optional |
| 8 | +from typing import List |
9 | 9 |
|
10 | 10 |
|
11 | 11 | 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):
|
48 | 48 | temp_new, matrix[rotated_row][rotated_col] = matrix[rotated_row][rotated_col], temp_new
|
49 | 49 |
|
50 | 50 |
|
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]]: |
56 | 52 | """
|
57 | 53 | Does the same as rotate_matrix, but in place.
|
58 | 54 | Runtime: O(N^2), asymptotic runtime depends on N. We make N^2 swaps.
|
59 | 55 | 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. |
61 | 56 | :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) |
65 | 57 | :return: the input matrix, but rotated
|
66 | 58 | """
|
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 |
75 | 66 |
|
76 | 67 |
|
77 | 68 | class TestRotateMatrixFunction(unittest.TestCase):
|
|
0 commit comments