Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions garrison_exercises/rotate_image/rotate_image.py
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions garrison_exercises/rotate_image/rotate_image_test.py
Original file line number Diff line number Diff line change
@@ -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]])