|
| 1 | +""" |
| 2 | +Python version 3.7.0 |
| 3 | +1.7 - Rotate Matrix |
| 4 | +Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate |
| 5 | +the image by 90 degrees. Can you do this in place? |
| 6 | +""" |
| 7 | +import unittest |
| 8 | +from typing import List, Callable |
| 9 | + |
| 10 | + |
| 11 | +def rotate_matrix(matrix: List[List[int]], N: int) -> List[List[int]]: |
| 12 | + """ |
| 13 | + Rotate matrix will rotate the given matrix by 90 degrees. |
| 14 | + Runtime: O(N^2), asymptotic runtime depends on N |
| 15 | + Space Complexity: O(N^2), creating a new matrix of NxN called 'rotated' |
| 16 | + :param matrix: an NxN matrix |
| 17 | + :param N: the size of the matrix (NxN) |
| 18 | + :return: a newly rotated matrix |
| 19 | + """ |
| 20 | + rotated = [[0 for i in range(N)] for j in range(N)] |
| 21 | + for i in range(N): |
| 22 | + for j in range(N): |
| 23 | + rotated[j][(N-1)-i] = matrix[i][j] |
| 24 | + return rotated |
| 25 | + |
| 26 | + |
| 27 | +def rotate_matrix_in_place(matrix: List[List[int]], N: int) -> List[List[int]]: |
| 28 | + """ |
| 29 | + Does the same as rotate_matrix, but in place. |
| 30 | + :param matrix: an NxN matrix |
| 31 | + :param N: the size of the matrix (NxN) |
| 32 | + :return: |
| 33 | + """ |
| 34 | + return matrix |
| 35 | + |
| 36 | + |
| 37 | +class TestRotateMatrixFunction(unittest.TestCase): |
| 38 | + def _run_tests(self, f: Callable[[List[List[int]], int], List[List[int]]]): |
| 39 | + cases = [ |
| 40 | + ( |
| 41 | + [ |
| 42 | + [1, 2, 3, 4], |
| 43 | + [5, 6, 7, 8], |
| 44 | + [9, 10, 11, 12], |
| 45 | + [13, 14, 15, 16] |
| 46 | + ], |
| 47 | + 4, |
| 48 | + [ |
| 49 | + [13, 9, 5, 1], |
| 50 | + [14, 10, 6, 2], |
| 51 | + [15, 11, 7, 3], |
| 52 | + [16, 12, 8, 4] |
| 53 | + ] |
| 54 | + ), |
| 55 | + ( |
| 56 | + [ |
| 57 | + [1, 2, 3], |
| 58 | + [4, 5, 6], |
| 59 | + [7, 8, 9] |
| 60 | + ], |
| 61 | + 3, |
| 62 | + [ |
| 63 | + [7, 4, 1], |
| 64 | + [8, 5, 2], |
| 65 | + [9, 6, 3] |
| 66 | + ] |
| 67 | + ), |
| 68 | + ( |
| 69 | + [ |
| 70 | + [1] |
| 71 | + ], |
| 72 | + 1, |
| 73 | + [ |
| 74 | + [1] |
| 75 | + ] |
| 76 | + ) |
| 77 | + ] |
| 78 | + for matrix, N, expected in cases: |
| 79 | + self.assertEqual(f(matrix, N), expected, msg=(matrix, N, expected)) |
| 80 | + |
| 81 | + def test_rotate_matrix(self): |
| 82 | + self._run_tests(rotate_matrix) |
| 83 | + # self._run_tests(rotate_matrix_in_place) |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == '__main__': |
| 87 | + unittest.main() |
0 commit comments