90 degree rotation of a NxN matrix

Q. 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?


"""
for i = 0 to n:
    temp = top[i]
    top[i] = left[i]
    left[i] = bottom[i]
    bottom[i] = right[i]
    right[i] = temp
"""

def rotate_matrix_90(matrix,n):
    
    for layer in range(0,n/2):
        first = layer
        last = n-1-layer
        
        for i in range(first,last):
            
            offset = i - first
            
            temp = matrix[first][i]
            matrix[first][i] = matrix[last-offset][first]
            matrix[last-offset][first] = matrix[last][last-offset]
            matrix[last][last-offset] = matrix[i][last]
            matrix[i][last] = temp
            
            
            
def transpose(m,n):
    return [list(x) for x in zip(*m)]
            
            
if __name__ == "__main__":
    
    matrix = [[1,0,3,2],[0,23,12,3],[0,0,0,34],[1,2,3,4]]
    
    for i in range(len(matrix)):
        print matrix[i]
            

    rotate_matrix_90(matrix,4)
    
    print "\n"
    for i in range(len(matrix)):
        print matrix[i]
        
    matrix = [[1,0,3,2],[0,23,12,3],[0,0,0,34],[1,2,3,4]]
    m = transpose(matrix,4)
    print "\n"
    for i in range(len(m)):
        print m[i]

    
    

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s