Open In App

Rotate matrix by 45 degrees

Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to rotate matrix by 45 degree
void matrix(int n, int m, vector<vector<int>> li)
{
     
    // Counter Variable
    int ctr = 0;
     
    while (ctr < 2 * n - 1)
    {
        for(int i = 0;
                i < abs(n - ctr - 1);
                i++)
        {
            cout << " ";
        }
         
        vector<int> lst;
 
        // Iterate [0, m]
        for(int i = 0; i < m; i++)
        {
             
            // Iterate [0, n]
            for(int j = 0; j < n; j++)
            {
                 
                // Diagonal Elements
                // Condition
                if (i + j == ctr)
                {
                     
                    // Appending the
                    // Diagonal Elements
                    lst.push_back(li[i][j]);
                }
            }
        }
             
        // Printing reversed Diagonal
        // Elements
        for(int i = lst.size() - 1; i >= 0; i--)
        {
            cout << lst[i] << " ";
        }
        cout << endl;
        ctr += 1;
    }
}
 
// Driver code   
int main()
{
     
    // Dimensions of Matrix
    int n = 8;
    int m = n;
     
    // Given matrix
    vector<vector<int>> li{
        { 4, 5, 6, 9, 8, 7, 1, 4 },
        { 1, 5, 9, 7, 5, 3, 1, 6 },
        { 7, 5, 3, 1, 5, 9, 8, 0 },
        { 6, 5, 4, 7, 8, 9, 3, 7 },
        { 3, 5, 6, 4, 8, 9, 2, 1 },
        { 3, 1, 6, 4, 7, 9, 5, 0 },
        { 8, 0, 7, 2, 3, 1, 0, 8 },
        { 7, 5, 3, 1, 5, 9, 8, 5 } };
     
    // Function call
    matrix(n, m, li);
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java




// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to rotate
// matrix by 45 degree
static void matrix(int n, int m,
                   int [][]li)
{
  // Counter Variable
  int ctr = 0;
 
  while (ctr < 2 * n - 1)
  {
    for(int i = 0; i < Math.abs(n - ctr - 1);
            i++)
    {
      System.out.print(" ");
    }
 
    Vector<Integer> lst = new Vector<Integer>();
 
    // Iterate [0, m]
    for(int i = 0; i < m; i++)
    {
      // Iterate [0, n]
      for(int j = 0; j < n; j++)
      {
        // Diagonal Elements
        // Condition
        if (i + j == ctr)
        {
          // Appending the
          // Diagonal Elements
          lst.add(li[i][j]);
        }
      }
    }
 
    // Printing reversed Diagonal
    // Elements
    for(int i = lst.size() - 1; i >= 0; i--)
    {
      System.out.print(lst.get(i) + " ");
    }
     
    System.out.println();
    ctr += 1;
  }
}
 
// Driver code   
public static void main(String[] args)
{   
  // Dimensions of Matrix
  int n = 8;
  int m = n;
 
  // Given matrix
  int[][] li = {{4, 5, 6, 9, 8, 7, 1, 4},
                {1, 5, 9, 7, 5, 3, 1, 6},
                {7, 5, 3, 1, 5, 9, 8, 0},
                {6, 5, 4, 7, 8, 9, 3, 7},
                {3, 5, 6, 4, 8, 9, 2, 1},
                {3, 1, 6, 4, 7, 9, 5, 0},
                {8, 0, 7, 2, 3, 1, 0, 8},
                {7, 5, 3, 1, 5, 9, 8, 5}};
 
  // Function call
  matrix(n, m, li);
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 program for the above approach
 
# Function to rotate matrix by 45 degree
 
 
def matrix(n, m, li):
 
    # Counter Variable
    ctr = 0
    while(ctr < 2 * n-1):
        print(" "*abs(n-ctr-1), end ="")
        lst = []
 
        # Iterate [0, m]
        for i in range(m):
 
                # Iterate [0, n]
            for j in range(n):
 
                # Diagonal Elements
                # Condition
                if i + j == ctr:
 
                    # Appending the
                    # Diagonal Elements
                    lst.append(li[i][j])
 
        # Printing reversed Diagonal
        # Elements
        lst.reverse()
        print(*lst)
        ctr += 1
 
 
# Driver Code
 
# Dimensions of Matrix
n = 8
m = n
 
# Given matrix
li = [[4, 5, 6, 9, 8, 7, 1, 4],
      [1, 5, 9, 7, 5, 3, 1, 6],
      [7, 5, 3, 1, 5, 9, 8, 0],
      [6, 5, 4, 7, 8, 9, 3, 7],
      [3, 5, 6, 4, 8, 9, 2, 1],
      [3, 1, 6, 4, 7, 9, 5, 0],
      [8, 0, 7, 2, 3, 1, 0, 8],
      [7, 5, 3, 1, 5, 9, 8, 5]]
 
# Function Call
matrix(n, m, li)


C#




// C# program for
// the above approach
using System;
using System.Collections;
class GFG{
  
// Function to rotate
// matrix by 45 degree
static void matrix(int n, int m,
                   int [,]li)
{
  // Counter Variable
  int ctr = 0;
 
  while (ctr < 2 * n - 1)
  {
    for(int i = 0;
            i < Math.Abs(n - ctr - 1);
            i++)
    {
      Console.Write(" ");
    }
 
    ArrayList lst = new ArrayList();
 
    // Iterate [0, m]
    for(int i = 0; i < m; i++)
    {
      // Iterate [0, n]
      for(int j = 0; j < n; j++)
      {
        // Diagonal Elements
        // Condition
        if (i + j == ctr)
        {
          // Appending the
          // Diagonal Elements
          lst.Add(li[i, j]);
        }
      }
    }
 
    // Printing reversed Diagonal
    // Elements
    for(int i = lst.Count - 1;
            i >= 0; i--)
    {
      Console.Write((int)lst[i] + " ");
    }
 
    Console.Write("\n");
    ctr += 1;
  }
}
  
// Driver code   
public static void Main(string[] args)
{   
  // Dimensions of Matrix
  int n = 8;
  int m = n;
  
  // Given matrix
  int[,] li = {{4, 5, 6, 9, 8, 7, 1, 4},
               {1, 5, 9, 7, 5, 3, 1, 6},
               {7, 5, 3, 1, 5, 9, 8, 0},
               {6, 5, 4, 7, 8, 9, 3, 7},
               {3, 5, 6, 4, 8, 9, 2, 1},
               {3, 1, 6, 4, 7, 9, 5, 0},
               {8, 0, 7, 2, 3, 1, 0, 8},
               {7, 5, 3, 1, 5, 9, 8, 5}};
  
  // Function call
  matrix(n, m, li);
}
}
 
// This code is contributed by Rutvik_56


Javascript




<script>
 
// Javascript program to rotate a matrix by 45 degrees
 
// A function to rotate a matrix
// mat[][] of size R x C.
// Initially, m = R and n = C
function matrix(m, n, mat)
{
    let ctr = 0;
     
    while(ctr < 2*n-1)
    {
        for(let i = 0; i < Math.abs(n-ctr-1); i++)
        {
            document.write(" ");
        }
     
    var list = [];
    // Iterate [0, m]
    for(let i = 0; i < m; i++)
    {
          
        // Iterate [0, n]
        for(let j = 0; j < n; j++)
        {
              
            // Diagonal Elements
            // Condition
            if (i + j == ctr)
            {
                  
                // Appending the
                // Diagonal Elements
                list.push(mat[i][j]);
            }
        }
    }
 
    // Print rotated matrix
    for(let i = list.length-1; i >= 0; i--)
    {
            document.write(list[i] + " ");
    }       
        document.write("<br>");
        ctr+=1;
    }
 
}
 
// Driver code
 
// Test Case 1
let R = 8;
let C = 8;
let a = [ [ 4, 5, 6, 9, 8, 7, 1, 4 ],
        [ 1, 5, 9, 7, 5, 3, 1, 6 ],
        [ 7, 5, 3, 1, 5, 9, 8, 0 ],
        [ 6, 5, 4, 7, 8, 9, 3, 7 ],
        [ 3, 5, 6, 4, 8, 9, 2, 1 ],
        [ 3, 1, 6, 4, 7, 9, 5, 0 ],
        [ 8, 0, 7, 2, 3, 1, 0, 8 ],
        [ 7, 5, 3, 1, 5, 9, 8, 5 ]  ];
         
matrix(R, C, a);
 
// This code is contributed by Aarti_Rathi
 
</script>


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:

C++




#include <bits/stdc++.h>
using namespace std;
  
// function to print the matrix rotated at 45 degree.
void rotate(int m, int n, int* a)
{
    // for printing the first half of matrix
    for (int i = 0; i < m; i++) {
  
        // print spaces
        for (int k = 0; k < m - i; k++) {
            cout << " ";
        }
        // counter to keep a track of the number of elements
        // left for the current diagonal
        int c = min(m - 1, min(i, n - 1));
  
        // to access the diagonal elements
        int inc = 0;
  
        // while loop prints the diagonal elements of the
        // current loop.
        while (i <= m - 1 && c != -1) {
            cout << *(a + (i - inc) * n + inc)  << " ";
  
            // increasing this variable to reach the
            // remaining elements of the diagonal
            inc++;
  
            // decreasing the counter to as an element is
            // printed
            c--;
        }
  
        cout << endl;
    }
  
    // for printing second half of the matrix
    for (int j = 1; j < n; j++) {
  
        // print spaces
        if (m < n) {
            for (int k = 0; k <= j - 1; k++) {
                cout << " ";
            }
        }
        else{
            for (int k = 0; k <= j; k++) {
                cout << " ";
            }
        }
          
  
        // counter to keep a track of the number of elements
        // left for the current diagonal
        int c2 = min(m - 1, n - j - 1);
  
        // to access the diagonal elements
        int inc2 = 0;
  
        // while loop prints the diagonal elements of the
        // current loop.
        while (j <= n - 1 && c2 != -1) {
            cout << *((a + (m - 1 - inc2) * n) + j + inc2)
                 << " ";
            inc2++;
            c2--;
        }
  
        cout << endl;
    }
}
// Driver code
int main()
{
    int m = 6;
    int n = m;
    int a[m][n] = {
        {3,4,5,1,5,9},
        {6,9,8,7,2,5},
        {1,5,9,7,5,3},
        {4,7,8,9,3,5},
        {4,5,2,9,5,6},
        {4,5,7,2,9,8}
    };
    rotate(m, n, (int*)a);
    return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    // function to print the matrix rotated at 45 degree.
    static void rotate(int m, int n, int[] a) {
        // printing first half of matrix
        for (int i = 0; i < m; i++) {
 
            // print space
            for (int k = 0; k < m - i; k++) {
                System.out.print(" ");
            }
            // counter to keep a track of the number of elements left
           
            int c = Math.min(m - 1, Math.min(i, n - 1));
 
            //for the diagonal elements
            int inc = 0;
 
            // prints the diagonal elements of the loop.
           
            while (i <= m - 1 && c != -1) {
                System.out.print(a[(i - inc) * n + inc] + " ");
 
                // increasing the variable to reach the remaining elements
                inc++;
 
                // decreasing the counter to as an element is printed
                c--;
            }
 
            System.out.println();
        }
 
        // for printing second half of the matrix
        for (int j = 1; j < n; j++) {
 
            // print spaces
            if (m < n) {
                for (int k = 0; k <= j - 1; k++) {
                    System.out.print(" ");
                }
            } else {
                for (int k = 0; k <= j; k++) {
                    System.out.print(" ");
                }
            }
 
            // counter to keep a track of the number of elements left
           
            int c2 = Math.min(m - 1, n - j - 1);
 
            // to access the diagonal elements
            int inc2 = 0;
 
            // while loop prints the diagonal elements
           
            while (j <= n - 1 && c2 != -1) {
                System.out.print(a[(m - 1 - inc2) * n + j + inc2] + " ");
                inc2++;
                c2--;
            }
 
            System.out.println();
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int m = 6;
        int n = m;
        int[][] a = {
                {3, 4, 5, 1, 5, 9},
                {6, 9, 8, 7, 2, 5},
                {1, 5, 9, 7, 5, 3},
                {4, 7, 8, 9, 3, 5},
                {4, 5, 2, 9, 5, 6},
                {4, 5, 7, 2, 9, 8}
        };
        int[] flattenedArray = new int[m * n];
        int idx = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                flattenedArray[idx++] = a[i][j];
            }
        }
        rotate(m, n, flattenedArray);
    }
}


Python3




# Python program to rotate a matrix by 45 degrees
 
# A function to rotate a matrix
# mat[][] of size R x C.
# Initially, m = R and n = C
def matrix(m, n, a):
    # for printing the first half of matrix
    for i in range(m):
        # print spaces
        for k in range(m-i):
            print(" ", end="")
 
        # counter to keep a track of the number of elements
        # left for the current diagonal
        c = min(m - 1, min(i, n - 1))
 
        # to access the diagonal elements
        inc = 0
 
        # while loop prints the diagonal elements of the
        # current loop.
        while (i <= m-1 and c != -1):
            print(a[i-inc][inc], end=" ")
            # increasing this variable to reach the
            # remaining elements of the diagonal
            inc += 1
 
            # decreasing the counter to as an element is
            # printed
            c = c-1
 
        print("")
 
    # for printing second half of the matrix
    for j in range(1, n):
        # print spaces
        if (m < n):
            for k in range(j):
                print(" ", end="")
        else:
            for k in range(j+1):
                print(" ", end="")
 
        # counter to keep a track of the number of elements
        # left for the current diagonal
        c2 = min(m - 1, n - j - 1)
 
        # to access the diagonal elements
        inc2 = 0
 
        # while loop prints the diagonal elements of the
        # current loop.
        while (j <= n - 1 and c2 != -1):
            print(a[m-1-inc2][j+inc2], end=" ")
            inc2 += 1
            c2 -= 1
        print("")
 
# Driver code
# Test Case 1
m = 6
n = 6
a = [[3, 4, 5, 1, 5, 9],
     [6, 9, 8, 7, 2, 5],
     [1, 5, 9, 7, 5, 3],
     [4, 7, 8, 9, 3, 5],
     [4, 5, 2, 9, 5, 6],
     [4, 5, 7, 2, 9, 8]]
 
matrix(m, n, a)


C#




// C# program for the above approach
 
using System;
 
public class Program
{
    // function to print the matrix rotated at 45 degree.
    public static void Rotate(int m, int n, int[] a)
    {
        // for printing the first half of matrix
        for (int i = 0; i < m; i++)
        {
 
            // print spaces
            for (int k = 0; k < m - i; k++)
            {
                Console.Write(" ");
            }
            // counter to keep a track of the number of elements
            // left for the current diagonal
            int c = Math.Min(m - 1, Math.Min(i, n - 1));
 
            // to access the diagonal elements
            int inc = 0;
 
            // while loop prints the diagonal elements of the
            // current loop.
            while (i <= m - 1 && c != -1)
            {
                Console.Write(a[(i - inc) * n + inc] + " ");
 
                // increasing this variable to reach the
                // remaining elements of the diagonal
                inc++;
 
                // decreasing the counter to as an element is
                // printed
                c--;
            }
 
            Console.WriteLine();
        }
 
        // for printing second half of the matrix
        for (int j = 1; j < n; j++)
        {
 
            // print spaces
            if (m < n)
            {
                for (int k = 0; k <= j - 1; k++)
                {
                    Console.Write(" ");
                }
            }
            else
            {
                for (int k = 0; k <= j; k++)
                {
                    Console.Write(" ");
                }
            }
 
 
            // counter to keep a track of the number of elements
            // left for the current diagonal
            int c2 = Math.Min(m - 1, n - j - 1);
 
            // to access the diagonal elements
            int inc2 = 0;
 
            // while loop prints the diagonal elements of the
            // current loop.
            while (j <= n - 1 && c2 != -1)
            {
                Console.Write(a[(m - 1 - inc2) * n + j + inc2] + " ");
                inc2++;
                c2--;
            }
 
            Console.WriteLine();
        }
    }
 
    // Driver code
    public static void Main()
    {
        int m = 6;
        int n = m;
        int[] a = {
            3, 4, 5, 1, 5, 9,
            6, 9, 8, 7, 2, 5,
            1, 5, 9, 7, 5, 3,
            4, 7, 8, 9, 3, 5,
            4, 5, 2, 9, 5, 6,
            4, 5, 7, 2, 9, 8
        };
        Rotate(m, n, a);
    }
}
 
// This code is contributed by codebraxnzt


Javascript




// Javascript program to rotate a matrix by 45 degrees
  
// A function to rotate a matrix
// mat[][] of size R x C.
// Initially, m = R and n = C
function matrix(m, n, a)
{
 
    // for printing the first half of matrix
    for (let i = 0; i < m; i++){
   
        // print spaces
        for (let k = 0; k < m - i; k++) {
            console.log(" ");
        }
        // counter to keep a track of the number of elements
        // left for the current diagonal
        let c = Math.min(m - 1, Math.min(i, n - 1));
   
        // to access the diagonal elements
        let inc = 0;
   
        // while loop prints the diagonal elements of the
        // current loop.
        while (i <= m - 1 && c != -1) {
            console.log(a[i-inc][inc] + " ");
   
            // increasing this variable to reach the
            // remaining elements of the diagonal
            inc++;
   
            // decreasing the counter to as an element is
            // printed
            c--;
        }
        console.log("\n");
    }
   
    // for printing second half of the matrix
    for (let j = 1; j < n; j++) {
   
        // print spaces
        if (m < n) {
            for (let k = 0; k <= j - 1; k++) {
                console.log(" ");
            }
        }
        else{
            for (let k = 0; k <= j; k++) {
                console.log(" ");
            }
        }
           
   
        // counter to keep a track of the number of elements
        // left for the current diagonal
        let c2 = Math.min(m - 1, n - j - 1);
   
        // to access the diagonal elements
        let inc2 = 0;
   
        // while loop prints the diagonal elements of the
        // current loop.
        while (j <= n - 1 && c2 != -1) {
            console.log(a[m-1-inc2][j+inc2] + " ");
            inc2++;
            c2--;
        }
        console.log("\n");
    }
  
}
  
// Driver code
  
// Test Case 1
let m = 6;
let n = 6;
let a = [ [ 3,4,5,1,5,9 ],
        [ 6,9,8,7,2,5 ],
        [ 1,5,9,7,5,3 ],
        [ 4,7,8,9,3,5 ],
        [ 4,5,2,9,5,6 ],
        [ 4,5,7,2,9,8 ]];
          
matrix(m, n, a);


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)



Last Updated : 16 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads