diff --git a/garrison_exercises/rotate_image/rotate_image.py b/garrison_exercises/rotate_image/rotate_image.py new file mode 100644 index 0000000..4bde812 --- /dev/null +++ b/garrison_exercises/rotate_image/rotate_image.py @@ -0,0 +1,27 @@ +""" +https://leetcode.com/problems/rotate-image/ + +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). + +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. +""" + +from typing import List + + +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + n = len(matrix) + """ + Do not return anything, modify matrix in-place instead. + """ + # Note: // means floor division in Python i.e + # rounding down to the nearest integer + + for i in range(n // 2 + n %2): + for j in range(n // 2): + temp = matrix[n - 1 - j][i] + matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1] + matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] + matrix[j][n - 1 - i] = matrix[i][j] + matrix[i][j] = temp \ No newline at end of file diff --git a/garrison_exercises/rotate_image/rotate_image_test.py b/garrison_exercises/rotate_image/rotate_image_test.py new file mode 100644 index 0000000..1f9d833 --- /dev/null +++ b/garrison_exercises/rotate_image/rotate_image_test.py @@ -0,0 +1,16 @@ +#from leetcode_practice.garrison_exercises.rotate_image.rotate_image import Solution +""" +import pathlib +filepath = pathlib.Path(__file__).absolute() # gets the path of the current file +""" + +import sys +from typing import List + +from .rotate_image import * + +def test_size4_matrix() -> None: + input_matrix: List[List[int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + output_matrix: List[List[int]] = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] + assert(Solution.rotate(input_matrix) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]) +