Rotate the MatrixThis article will see the code that will rotate the given matrix elements clockwise. To visualize the problem, let us first look at some examples of matrix rotation. Examples of rotation of matrix: For 3 * 3 matrix Input Output: 2 1 4 3 5 7 6 9 8 For 4 * 4 matrix Input: Output: 2 1 5 9 3 7 6 13 4 11 10 14 8 12 16 15 Approach - 1This question is similar to another question about the matrix where we have to print the spiral form of the matrix. We will use similar loops, but we have to do it according to the rings this time. We have to rotate all the rings of the elements one by one, starting from the ring that makes the border of the matrix. We will follow the following steps to rotate a ring of the matrix:
Below is the Python code that uses the abovementioned approach to solve the problem and rotate the given matrix. Code Output: Rotated matrix1: [2, 1, 4] [3, 5, 7] [6, 9, 8] Rotated matrix2: [2, 1, 5, 9] [3, 7, 6, 13] [4, 11, 10, 14] [8, 12, 16, 15] Time Complexity: O(max(m, n) * max(m, n)) is the time complexity of this program where m is the number of rows and n is the number of columns in the matrix Auxiliary Space: This program will take O(m * n) extra memory space Next TopicWater Quality Analysis |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India