Skip to content

Instantly share code, notes, and snippets.

@humbroll
Last active August 13, 2016 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbroll/67f84294def81bc698d86ab22c3f1d61 to your computer and use it in GitHub Desktop.
Save humbroll/67f84294def81bc698d86ab22c3f1d61 to your computer and use it in GitHub Desktop.
Rotate Matrix
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Rotate Matrix
# Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes,
# write a method to rotate the image by 90 degrees. Can you do this in place?
import copy
class RotateMatrix:
def __init__(self, org_matrix):
self.org_matrix = org_matrix
self.size = len(self.org_matrix)
def rotate(self):
result = copy.deepcopy(self.org_matrix)
for i, row in enumerate(self.org_matrix):
for j, ele in enumerate(row):
x = i + (-i+j)
y = j + ((self.size-1)-i-j)
result[x][y] = ele
return result
def print_matrix(self, matrix):
return "\n".join([str(m) for m in matrix])
if __name__ == '__main__':
matrix = \
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix_2 = \
[
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12],
[13,14,15,16],
]
matrix_3 = \
[
[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25],
]
rotate_matrix = RotateMatrix(matrix)
rotated_matrix = rotate_matrix.rotate()
print "INPUT"
print rotate_matrix.print_matrix(matrix)
print "OUTPUT"
print rotate_matrix.print_matrix(rotated_matrix)
@humbroll
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment