Matrix Rotation

June 6, 2017

We have a two-part exercise today, based on a Microsoft interview question.

First, write a program to rotate an m × n matrix 90° to the right, as shown below; your solution should touch each matrix element only once:

    a b c
    d e f                 m j g d a
A = g h i        rot(A) = n k h e b
    j k l                 o l i f c
    m n o

Second, write a program to rotate a square matrix with n rows and columns in-place. where the source and target matrices are the same matrix and there is no intermediate matrix (be sure your solution works for both even and odd n):

    a b c d e                 u p k f a
    f g h i j                 v q l g b
B = k l m n o        rot(B) = w r m h c
    p q r s t                 x s n i d
    u v w x y                 y t o j e

Your task is to write the two programs that rotate matrices. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2