Exercise Beginner: Rotate matrix 90 degrees

Request:
Write a program that rotates the given matrix 90 degrees clockwise. The matrix size is n × m. (1 ≤ n, m ≤ 50, -10^9 <= matrix elements <= 10^9). Print the rotated matrix in the same format like input.

Solution
We will solve this problem with a concrete case, by using the matrix shown bellow:

Example code:

and the result for this specific case should be as follow:

Example code:

In order to reach such result we need the result matrix hight to be same as the input matrix width and the result matrix width to be same with the input matrix height. The new location

In order to have a matrix in code we have to declare a two dimensional array as seen bellow.

Example code:

In order to implement the logic described bellow we will have to write the following code.

Example code:

All the elements used on this exercise are covered in the published lessons except the 2-dimensional array, which has pretty much the same logic as 1-dimensional array and multi-dimensional arrays. 1-dimensional arrays are covered at lesson 8. We have not covered access modifiers(public, private, static), but they do not affect the logic of the code so far, so do not worry about them, they will be covered in the intermediate level because they are related with other concepts as well. All the logic of the algorithm, changing the size of the array, switching the location of the elements, is implemente at the rotateMatrix method. The other method, showMarix, is just a helper method which gets as parameter a 2-dimensional matrix and prints them so we do not need to write the code within this method in the main method every time we need to print a 2-dimensional matrix. The result of the execution is shown in the fiugre 1 bellow.


Figure 1: Execution


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game