VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-matrix-by-45-degrees/

⇱ Rotate matrix by 45 degrees - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate matrix by 45 degrees

Last Updated : 15 Jul, 2025

Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix.

Examples:

Input: N = 6, 
mat[][] = {{3, 4, 5, 1, 5, 9, 5}, 
               {6, 9, 8, 7, 2, 5, 2},  
               {1, 5, 9, 7, 5, 3, 2}, 
               {4, 7, 8, 9, 3, 5, 2}, 
               {4, 5, 2, 9, 5, 6, 2}, 
               {4, 5, 7, 2, 9, 8, 3}}
Output:
        3
      6 4
    1 9 5
   4 5 8 1
  4 7 9 7 5
4 5 8 7 2 9
  5 2 9 5 5
   7 9 3 3
    2 5 5
     9 6
      8

Input: N = 4, 
mat[][] = {{2, 5, 7, 2}, 
                {9, 1, 4, 3}, 
                {5, 8, 2, 3}, 
                {6, 4, 6, 3}}

Output:
    2
  9 5
 5 1 7
6 8 4 2
 4 2 3
  6 3
   3 

Approach 1: 

Follow the steps given below in order to solve the problem:

  1. Store the diagonal elements in a list using a counter variable.
  2. Print the number of spaces required to make the output look like the desired pattern.
  3. Print the list elements after reversing the list.
  4. Traverse through only diagonal elements to optimize the time taken by the operation.

Below is the implementation of the above approach:


Output
 4 
 1 5 
 7 5 6 
 6 5 9 9 
 3 5 3 7 8 
 3 5 4 1 5 7 
 8 1 6 7 5 3 1 
7 0 6 4 8 9 1 4 
 5 7 4 8 9 8 6 
 3 2 7 9 3 0 
 1 3 9 2 7 
 5 1 5 1 
 9 0 0 
 8 8 
 5 

Time Complexity: O(N3)
Auxiliary Space: O(N)

Approach 2: 

 (by rythmrana2)

Follow the given steps to print the matrix rotated by 45 degree:

  1. print the spaces required.
  2. print the element this way -

          traverse the matrix the way you want to print it

  • We will print the matrix by dividing it into two parts using two for loops , the first loop will print the first triangle of the matrix and the second loop will print the second triangle of the matrix
  • for the first half of matrix, take a loop that goes from the first row to the last row of the matrix.
  • at each row , take a while loop which prints the first element of the row and the second element of the row above the current row and the third element of the row which is twice above the current row, going this way we will print the first half triangle of the matrix.
  • take two counters, c for counting how many more elements the current diagonal have and counter inc for accessing those elements.
  • similarly do this for the second half of the matrix.

Below is the implementation of the above approach:


Output
 3 
 6 4 
 1 9 5 
 4 5 8 1 
 4 7 9 7 5 
 4 5 8 7 2 9 
 5 2 9 5 5 
 7 9 3 3 
 2 5 5 
 9 6 
 8 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Comment
Article Tags: