Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction

Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements.
Examples:
Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1
Output:
 1 16 11 6 5 Â
 22 7 12 9 2
 23 18 13 8 3
 24 17 14 19 4
 21 20 15 10 25Input: mat[][] = {{10, 11}, {12, 13}}, K = 2
Output:
10 11
12 13
Approach: The given problem can be solved by using the idea discussed in this article and the fact that the matrix restores after performing clockwise rotation 4 times. Follow the below steps to solve the given problem:
- Update the value of K as K % 4.
- Iterate until K is a positive and perform the following steps:
- Traverse the matrix, for i over the range [0, N / 2) and j over the range[0, N – i – 1) and perform the following steps:
- If the value of i != j and (i + j) != (N – 1), then perform the following steps:
- Store the value of mat[i][j] in a temporary variable temp.
- Update the value of mat[i][j] as mat[N – 1 – j][i].
- Update the value of mat[N – 1 – j][i] as mat[N – 1 -i][N – 1 – j].
- Update the value of mat[N – 1  – i][N – 1 – j] as mat[j][N – 1 – i].
- Update the value of mat[j][N – 1 – i] as temp.
- After completing the above steps, print the updated matrix obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to print the matrixvoid print(vector<vector<int> >& mat){    // Iterate over the rows    for (int i = 0; i < mat.size(); i++) {Â
        // Iterate over the columns        for (int j = 0; j < mat[0].size(); j++)Â
            // Print the value            cout << setw(3) << mat[i][j];        cout << "\n";    }}Â
// Function to perform the swapping of// matrix elements in clockwise mannervoid performSwap(vector<vector<int> >& mat,                 int i, int j){    int N = mat.size();Â
    // Stores the last row    int ei = N - 1 - i;Â
    // Stores the last column    int ej = N - 1 - j;Â
    // Perform the swaps    int temp = mat[i][j];    mat[i][j] = mat[ej][i];    mat[ej][i] = mat[ei][ej];    mat[ei][ej] = mat[j][ei];    mat[j][ei] = temp;}Â
// Function to rotate non - diagonal// elements of the matrix K times in// clockwise directionvoid rotate(vector<vector<int> >& mat,            int N, int K){    // Update K to K % 4    K = K % 4;Â
    // Iterate until K is positive    while (K--) {Â
        // Iterate each up to N/2-th row        for (int i = 0; i < N / 2; i++) {Â
            // Iterate each column            // from i to N - i - 1            for (int j = i;                 j < N - i - 1; j++) {Â
                // Check if the element                // at i, j is not a                // diagonal element                if (i != j                    && (i + j) != N - 1) {Â
                    // Perform the swapping                    performSwap(mat, i, j);                }            }        }    }Â
    // Print the matrix    print(mat);}Â
// Driver Codeint main(){    int K = 5;    vector<vector<int> > mat = {        { 1, 2, 3, 4 },        { 6, 7, 8, 9 },        { 11, 12, 13, 14 },        { 16, 17, 18, 19 },    };    int N = mat.size();    rotate(mat, N, K);Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*;Â
public class GFG {Â
    // Function to print the matrix    static void print(int mat[][])    {        // Iterate over the rows        for (int i = 0; i < mat.length; i++) {Â
            // Iterate over the columns            for (int j = 0; j < mat[0].length; j++)Â
                // Print the value                System.out.print(mat[i][j] + " ");                       System.out.println();        }    }Â
    // Function to perform the swapping of    // matrix elements in clockwise manner    static void performSwap(int mat[][], int i, int j)    {        int N = mat.length;Â
        // Stores the last row        int ei = N - 1 - i;Â
        // Stores the last column        int ej = N - 1 - j;Â
        // Perform the swaps        int temp = mat[i][j];        mat[i][j] = mat[ej][i];        mat[ej][i] = mat[ei][ej];        mat[ei][ej] = mat[j][ei];        mat[j][ei] = temp;    }Â
    // Function to rotate non - diagonal    // elements of the matrix K times in    // clockwise direction    static void rotate(int mat[][], int N, int K)    {        // Update K to K % 4        K = K % 4;Â
        // Iterate until K is positive        while (K-- > 0) {Â
            // Iterate each up to N/2-th row            for (int i = 0; i < N / 2; i++) {Â
                // Iterate each column                // from i to N - i - 1                for (int j = i; j < N - i - 1; j++) {Â
                    // Check if the element                    // at i, j is not a                    // diagonal element                    if (i != j && (i + j) != N - 1) {Â
                        // Perform the swapping                        performSwap(mat, i, j);                    }                }            }        }Â
        // Print the matrix        print(mat);    }       // Driver Code    public static void main(String[] args)    {Â
        int K = 5;        int mat[][] = {            { 1, 2, 3, 4 },            { 6, 7, 8, 9 },            { 11, 12, 13, 14 },            { 16, 17, 18, 19 },        };               int N = mat.length;        rotate(mat, N, K);    }}Â
// This code is contributed by Kingash. |
Python3
# Python3 program for the above approachÂ
# Function to print the matrixdef printMat(mat):       # Iterate over the rows    for i in range(len(mat)):Â
        # Iterate over the columns        for j in range(len(mat[0])):Â
            # Print the value            print(mat[i][j], end = " ")                     print()Â
# Function to perform the swapping of# matrix elements in clockwise mannerdef performSwap(mat, i, j):Â Â Â Â Â Â Â N = len(mat)Â
    # Stores the last row    ei = N - 1 - iÂ
    # Stores the last column    ej = N - 1 - jÂ
    # Perform the swaps    temp = mat[i][j]    mat[i][j] = mat[ej][i]    mat[ej][i] = mat[ei][ej]    mat[ei][ej] = mat[j][ei]    mat[j][ei] = tempÂ
# Function to rotate non - diagonal# elements of the matrix K times in# clockwise directiondef rotate(mat, N, K):Â
    # Update K to K % 4    K = K % 4Â
    # Iterate until K is positive    while (K > 0):Â
        # Iterate each up to N/2-th row        for i in range(int(N / 2)):Â
            # Iterate each column            # from i to N - i - 1            for j in range(i, N - i - 1):Â
                # Check if the element                # at i, j is not a                # diagonal element                if (i != j and (i + j) != N - 1):Â
                    # Perform the swapping                    performSwap(mat, i, j)                             K -= 1                         # Print the matrix    printMat(mat)Â
# Driver CodeK = 5mat = [ [ 1, 2, 3, 4 ],        [ 6, 7, 8, 9 ],        [ 11, 12, 13, 14 ],        [ 16, 17, 18, 19 ] ]N = len(mat)Â
rotate(mat, N, K)Â
# This code is contributed by Dharanendra L V. |
C#
// C# program for the above approachusing System;public class GFG {Â
    // Function to print the matrix    static void print(int[, ] mat)    {        // Iterate over the rows        for (int i = 0; i < mat.GetLength(0); i++) {Â
            // Iterate over the columns            for (int j = 0; j < mat.GetLength(1); j++)Â
                // Print the value                Console.Write(mat[i, j] + " ");Â
            Console.WriteLine();        }    }Â
    // Function to perform the swapping of    // matrix elements in clockwise manner    static void performSwap(int[, ] mat, int i, int j)    {        int N = mat.GetLength(0);Â
        // Stores the last row        int ei = N - 1 - i;Â
        // Stores the last column        int ej = N - 1 - j;Â
        // Perform the swaps        int temp = mat[i, j];        mat[i, j] = mat[ej, i];        mat[ej, i] = mat[ei, ej];        mat[ei, ej] = mat[j, ei];        mat[j, ei] = temp;    }Â
    // Function to rotate non - diagonal    // elements of the matrix K times in    // clockwise direction    static void rotate(int[, ] mat, int N, int K)    {        // Update K to K % 4        K = K % 4;Â
        // Iterate until K is positive        while (K-- > 0) {Â
            // Iterate each up to N/2-th row            for (int i = 0; i < N / 2; i++) {Â
                // Iterate each column                // from i to N - i - 1                for (int j = i; j < N - i - 1; j++) {Â
                    // Check if the element                    // at i, j is not a                    // diagonal element                    if (i != j && (i + j) != N - 1) {Â
                        // Perform the swapping                        performSwap(mat, i, j);                    }                }            }        }Â
        // Print the matrix        print(mat);    }Â
    // Driver Code    public static void Main(string[] args)    {Â
        int K = 5;        int[, ] mat = {            { 1, 2, 3, 4 },            { 6, 7, 8, 9 },            { 11, 12, 13, 14 },            { 16, 17, 18, 19 },        };Â
        int N = mat.GetLength(0);        rotate(mat, N, K);    }}Â
// This code is contributed by ukasp. |
Javascript
<script>Â
// Javascript implementation of the above approachÂ
   // Function to print the matrix    function print(mat)    {        // Iterate over the rows        for (let i = 0; i < mat.length; i++) {              // Iterate over the columns            for (let j = 0; j < mat[0].length; j++)                  // Print the value                document.write(mat[i][j] + " ");                        document.write("<br/>");        }    }      // Function to perform the swapping of    // matrix elements in clockwise manner    function performSwap(mat, i, j)    {        let N = mat.length;          // Stores the last row        let ei = N - 1 - i;          // Stores the last column        let ej = N - 1 - j;          // Perform the swaps        let temp = mat[i][j];        mat[i][j] = mat[ej][i];        mat[ej][i] = mat[ei][ej];        mat[ei][ej] = mat[j][ei];        mat[j][ei] = temp;    }      // Function to rotate non - diagonal    // elements of the matrix K times in    // clockwise direction    function rotate(mat, N, K)    {        // Update K to K % 4        K = K % 4;          // Iterate until K is positive        while (K-- > 0) {              // Iterate each up to N/2-th row            for (let i = 0; i < N / 2; i++) {                  // Iterate each column                // from i to N - i - 1                for (let j = i; j < N - i - 1; j++) {                      // Check if the element                    // at i, j is not a                    // diagonal element                    if (i != j && (i + j) != N - 1) {                          // Perform the swapping                        performSwap(mat, i, j);                    }                }            }        }          // Print the matrix        print(mat);    }Â
  // Driver Code          let K = 5;        let mat = [            [ 1, 2, 3, 4 ],            [ 6, 7, 8, 9 ],            [ 11, 12, 13, 14 ],            [ 16, 17, 18, 19 ],        ];                let N = mat.length;        rotate(mat, N, K);       </script> |
1 11 6 4 17 7 8 2 18 12 13 3 16 14 9 19
Â
Time Complexity: O(N2)
Auxiliary Space: O(1), since no extra space has been taken.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



