Rotating a Matrix [Java][C++]

This is a simple way of rotating a matrix clockwise or counter-clockwise. I will use Java to demonstrate. First, notice the pattern when you are rotating a matrix’ values clockwise:

Original 3 x 3 matrix:

[1][2][3]
[4][5][6]
[7][8][9]

Rotating last row:
[2][0] => [0][0]
[2][1] => [1][0]
[2][2] => [2][0]

Rotating middle row:
[1][0] => [0][1]
[1][1] => [1][1]
[1][2] => [2][1]

Rotating last row:
[0][0] => [0][2]
[0][1] => [1][2]
[0][2] => [2][2]

Note that you will need two loops for each row rotation.
One for incrementing through the row of the first matrix, and the second for incrementing through the rows and columns of the new matrix. In this method, we use a counter (z) for incrementing through each row of the new matrix while keeping the column the same.

Code:

 

Leave a Reply

Your email address will not be published. Required fields are marked *