Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rotates an N x N matrix M 90 degrees clockwise.
class Matrix:
@staticmethod
def rotate(m, n):
"""Rotates a matrix m of n x n size"""
# reverse each row of the matrix
for i in range(n):
m[i] = m[i][::-1]
# swap in place
src_col = n - 1
for i in range(n):
dest_col = 0
for j in range(n-1, -1, -1):
if i == j and src_col == dest_col:
break
else:
# swap the elements
m[i][dest_col], m[j][src_col] = m[j][src_col], m[i][dest_col]
dest_col += 1
src_col -= 1
return m
import unittest
class TestMatrix(unittest.TestCase):
def test_two_by_two(self):
M = [
[1, 2],
[3, 4]]
n = 2
R = [
[3, 1],
[4, 2]]
self.assertEqual(Matrix.rotate(M, n), R)
def test_three_by_three(self):
M = [
[1,2,3],
[4,5,6],
[7,8,9]]
n = 3
R = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
self.assertEqual(Matrix.rotate(M, n), R)
def test_four_by_four(self):
M = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
n = 4
R = [
[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 11, 7, 3],
[16, 12, 8, 4]]
self.assertEqual(Matrix.rotate(M, n), R)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment