Posted on by Kalkicode
Code Matrix

Inplace rotate square matrix by 90 degrees

The problem is to rotate a given square matrix (2D array) by 90 degrees in place, i.e., without using any additional memory. The rotation should be done clockwise.

Example

Consider the following square matrix:

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 26 27 28 29 30
31 32 33 34 35 36

After rotating the matrix by 90 degrees clockwise, it becomes:

6  12 18 24 30 36
5  11 17 23 29 35
4  10 16 22 28 34
3  9  15 21 27 33
2  8  14 20 26 32
1  7  13 19 25 31

Idea to Solve the Problem

To rotate the matrix in place, we can divide the task into three steps:

  1. First, we transpose the matrix. Transposing a matrix means swapping its elements across its main diagonal (i.e., swapping matrix[i][j] with matrix[j][i]).

  2. Next, we reverse each row of the transposed matrix. Reversing a row means swapping its elements from both ends.

  3. The resulting matrix after transposing and reversing each row will be the matrix rotated by 90 degrees clockwise.

Algorithm

  1. Create a function rotate_90_degree to perform the rotation.
  2. Perform the transposition of the matrix by swapping elements matrix[i][j] with matrix[j][i] for all i and j where i < j.
  3. Reverse each row of the transposed matrix.
  4. The matrix is now rotated by 90 degrees clockwise.

Pseudocode

rotate_90_degree(matrix, size):
    Transpose the matrix
    Reverse each row of the matrix

Code Solution

/*
    C Program 
    Inplace rotate square matrix by 90 degrees
*/
#include <stdio.h>

#define SIZE 6
//Rotate the square matrix element in 90 degrees
void rotate_90_degree(int matrix[SIZE][SIZE])
{
    //Define loop control variables
    int i = 1;
    int j = 0;
    int temp = 0;
    // Diagonal transform the elements of upper triangular matrix
    // Example
    /*
        /  /  / 
       /  /      Upper Triangular
      /
      ------------

      1   2   3
      4   5      Element Like this
      6
      -------------  


      1   4   6
      2   5       After transform
      3
      -------------  

    */
    for (i = 1; i < SIZE; ++i)
    {
        j = 0;
        while (j < i)
        {
            temp = matrix[j][i - j];
            matrix[j][i - j] = matrix[i - j][j];
            matrix[i - j][j] = temp;
            j++;
        }
    }
    // Diagonal transform the elements of lower triangular matrix
    // Example
    /*
        /
       /  /  
      /  /  /   Lower Triangular
      -------

            1   
         2  3   Element Like this
      4  5  6 
     
      -------------  

            4  
         2  5   After transform
      1  3  6 
      -------------  

    */
    for (i = 1; i < SIZE - 1; ++i)
    {
        j = 0;
        while (j < i)
        {
            temp = matrix[i - j][(SIZE - 1) - j];
            matrix[i - j][(SIZE - 1) - j] = matrix[(SIZE - 1) - j][i - j];
            matrix[(SIZE - 1) - j][i - j] = temp;
            j++;
        }
    }
    // Invert column values
    /*
        |  |  |  |
        |  |  |  |  pattern
        |  |  |  |
        |  |  |  |
     
      -------

        1   5   9   13
        2   6   10  14  Element Like this
        3   7   11  15
        4   9   12  16
      -------------  

        4   9   12  16
        3   7   11  15  After transform
        2   6   10  14
        1   5   9   13
      -------------  

    */
    for (i = 0; i < SIZE; ++i)
    {
        for (j = 0; j < SIZE / 2; ++j)
        {
            temp = matrix[j][i];
            matrix[j][i] = matrix[(SIZE - 1) - j][i];
            matrix[(SIZE - 1) - j][i] = temp;
        }
    }
}
//Display matrix elements
void show_data(int matrix[SIZE][SIZE])
{
    int i = 0;
    int j = 0;
    for (i = 0; i < SIZE; ++i)
    {
        for (j = 0; j < SIZE; ++j)
        {
            printf("%3d", matrix[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
int main()
{
    int matrix[SIZE][SIZE] = 
    {
        {
            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 , 26 , 27 , 28 , 29 , 30
        } ,
        {
            31 , 32 , 33 , 34 , 35 , 36
        }
    };
    printf("\n Before rotate \n");
    show_data(matrix);
    rotate_90_degree(matrix);
    printf("\n After rotate \n");
    show_data(matrix);
    return 0;
}

Output

 Before rotate
  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 26 27 28 29 30
 31 32 33 34 35 36


 After rotate
  6 12 18 24 30 36
  5 11 17 23 29 35
  4 10 16 22 28 34
  3  9 15 21 27 33
  2  8 14 20 26 32
  1  7 13 19 25 31
/*
    Java Program 
    Inplace rotate square matrix by 90 degrees
*/


public class MyMatrix
{
    //Rotate the square matrix element in 90 degrees
    public void rotate_90_degree(int [][]matrix,int size)
    {
        //Define loop control variables
        int i = 1;
        int j = 0;
        int temp = 0;
        // Diagonal transform the elements of upper triangular matrix
        // Example
        /*
                /  /  / 
               /  /      Upper Triangular
              /
              ------------

              1   2   3
              4   5      Element Like this
              6
              -------------  


              1   4   6
              2   5       After transform
              3
              -------------  

            */
        for (i = 1; i < size; ++i)
        {
            j = 0;
            while (j < i)
            {
                temp = matrix[j][i - j];
                matrix[j][i - j] = matrix[i - j][j];
                matrix[i - j][j] = temp;
                j++;
            }
        }
        // Diagonal transform the elements of lower triangular matrix
        // Example
        /*
                /
               /  /  
              /  /  /   Lower Triangular
              -------

                    1   
                 2  3   Element Like this
              4  5  6 
             
              -------------  

                    4  
                 2  5   After transform
              1  3  6 
              -------------  

            */
        for (i = 1; i < size - 1; ++i)
        {
            j = 0;
            while (j < i)
            {
                temp = matrix[i - j][(size - 1) - j];
                matrix[i - j][(size - 1) - j] = matrix[(size - 1) - j][i - j];
                matrix[(size - 1) - j][i - j] = temp;
                j++;
            }
        }
        // Invert column values
        /*
            |  |  |  |
            |  |  |  |  pattern
            |  |  |  |
            |  |  |  |
         
            -------

            1   5   9   13
            2   6   10  14  Element Like this
            3   7   11  15
            4   9   12  16
            -------------  

            4   9   12  16
            3   7   11  15  After transform
            2   6   10  14
            1   5   9   13
            -------------  

        */
        for (i = 0; i < size; ++i)
        {
            for (j = 0; j < size / 2; ++j)
            {
                temp = matrix[j][i];
                matrix[j][i] = matrix[(size - 1) - j][i];
                matrix[(size - 1) - j][i] = temp;
            }
        }
    }
    //Display matrix elements
    public void show_data(int[][] matrix,int size)
    {
        int i = 0;
        int j = 0;
        for (i = 0; i < size; ++i)
        {
            for (j = 0; j < size; ++j)
            {
                System.out.print("  " + matrix[i][j] );
            }
            System.out.print("\n");
        }
        System.out.print("\n");
    }
       
    public static void main(String[] args)
    {
       
        MyMatrix obj = new MyMatrix();

        int[][] matrix =  {
            {
                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 , 26 , 27 , 28 , 29 , 30
            } , {
                31 , 32 , 33 , 34 , 35 , 36
            }
        };

        int size = matrix[0].length;
        System.out.print("\n Before rotate \n");
        obj.show_data(matrix,size);
        obj.rotate_90_degree(matrix,size);
        System.out.print("\n After rotate \n");
        obj.show_data(matrix,size);
    }
}

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
// Include header file
#include <iostream>
#define SIZE  6
using namespace std;
/*
    C++ Program 
    Inplace rotate square matrix by 90 degrees
*/
class MyMatrix
{
	public:
		// Rotate the square matrix element in 90 degrees
		void rotate_90_degree(int matrix[SIZE][SIZE])
		{
			// Define loop control variables
			int i = 1;
			int j = 0;
			int temp = 0;
			/*
			        Diagonal transform the elements of upper triangular matrix
			        Example
			        ----------------------------

			            /  /  / 
			           /  /      Upper Triangular
			          /
			        ----------------------------

			          1   2   3
			          4   5      Element Like this
			          6
			        -----------------------------


			          1   4   6
			          2   5       After transform
			          3
			        --------------------------------

			        */
			for (i = 1; i < SIZE; ++i)
			{
				j = 0;
				while (j < i)
				{
					temp = matrix[j][i - j];
					matrix[j][i - j] = matrix[i - j][j];
					matrix[i - j][j] = temp;
					j++;
				}
			}
			/*
			        // Diagonal transform the elements of lower triangular matrix
			        // Example
			        ---------------------------
			            /
			           /  /  
			          /  /  /   Lower Triangular
			          ---------------------------

			                1   
			             2  3   Element Like this
			          4  5  6 
			         
			          ------------------------------ 

			                4  
			             2  5   After transform
			          1  3  6 
			          ------------------------------  

			        */
			for (i = 1; i < SIZE - 1; ++i)
			{
				j = 0;
				while (j < i)
				{
					temp = matrix[i - j][(SIZE - 1) - j];
					matrix[i - j][(SIZE - 1) - j] = matrix[(SIZE - 1) - j][i - j];
					matrix[(SIZE - 1) - j][i - j] = temp;
					j++;
				}
			}
			/*
			        Invert column values

			            |  |  |  |
			            |  |  |  |  pattern
			            |  |  |  |
			            |  |  |  |
			         
			            -------

			            1   5   9   13
			            2   6   10  14  Element Like this
			            3   7   11  15
			            4   9   12  16
			            -------------  

			            4   9   12  16
			            3   7   11  15  After transform
			            2   6   10  14
			            1   5   9   13
			            -------------  

			        */
			for (i = 0; i < SIZE; ++i)
			{
				for (j = 0; j < SIZE / 2; ++j)
				{
					temp = matrix[j][i];
					matrix[j][i] = matrix[(SIZE - 1) - j][i];
					matrix[(SIZE - 1) - j][i] = temp;
				}
			}
		}
	// Display matrix elements
	void show_data(int matrix[SIZE][SIZE])
	{
		int i = 0;
		int j = 0;
		for (i = 0; i < SIZE; ++i)
		{
			for (j = 0; j < SIZE; ++j)
			{
				cout << "  " << matrix[i][j];
			}
			cout << "\n";
		}
		cout << "\n";
	}
};
int main()
{
	MyMatrix obj = MyMatrix();
	int matrix[SIZE][SIZE] = {
		{
			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 , 26 , 27 , 28 , 29 , 30
		} , {
			31 , 32 , 33 , 34 , 35 , 36
		}
	};

	cout << "\n Before rotate \n";
	obj.show_data(matrix);
	obj.rotate_90_degree(matrix);
	cout << "\n After rotate \n";
	obj.show_data(matrix);
	return 0;
}

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
// Include namespace system
using System;
/*
    C# Program 
    Inplace rotate square matrix by 90 degrees
*/
public class MyMatrix
{
	// Rotate the square matrix element in 90 degrees
	public void rotate_90_degree(int[,] matrix, int size)
	{
		// Define loop control variables
		int i = 1;
		int j = 0;
		int temp = 0;
		/*
		        Diagonal transform the elements of upper triangular matrix
		        Example
		        ----------------------------

		            /  /  / 
		           /  /      Upper Triangular
		          /
		        ----------------------------

		          1   2   3
		          4   5      Element Like this
		          6
		        -----------------------------


		          1   4   6
		          2   5       After transform
		          3
		        --------------------------------

		        */
		for (i = 1; i < size; ++i)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[j,i - j];
				matrix[j,i - j] = matrix[i - j,j];
				matrix[i - j,j] = temp;
				j++;
			}
		}
		/*
		        // Diagonal transform the elements of lower triangular matrix
		        // Example
		        ---------------------------
		            /
		           /  /  
		          /  /  /   Lower Triangular
		          ---------------------------

		                1   
		             2  3   Element Like this
		          4  5  6 
		         
		          ------------------------------ 

		                4  
		             2  5   After transform
		          1  3  6 
		          ------------------------------  

		        */
		for (i = 1; i < size - 1; ++i)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[i - j,(size - 1) - j];
				matrix[i - j,(size - 1) - j] = matrix[(size - 1) - j,i - j];
				matrix[(size - 1) - j,i - j] = temp;
				j++;
			}
		}
		/*
		        Invert column values

		            |  |  |  |
		            |  |  |  |  pattern
		            |  |  |  |
		            |  |  |  |
		         
		            -------

		            1   5   9   13
		            2   6   10  14  Element Like this
		            3   7   11  15
		            4   9   12  16
		            -------------  

		            4   9   12  16
		            3   7   11  15  After transform
		            2   6   10  14
		            1   5   9   13
		            -------------  

		        */
		for (i = 0; i < size; ++i)
		{
			for (j = 0; j < size / 2; ++j)
			{
				temp = matrix[j,i];
				matrix[j,i] = matrix[(size - 1) - j,i];
				matrix[(size - 1) - j,i] = temp;
			}
		}
	}
	// Display matrix elements
	public void show_data(int[,] matrix, int size)
	{
		int i = 0;
		int j = 0;
		for (i = 0; i < size; ++i)
		{
			for (j = 0; j < size; ++j)
			{
				Console.Write("  " + matrix[i,j]);
			}
			Console.Write("\n");
		}
		Console.Write("\n");
	}
	public static void Main(String[] args)
	{
		MyMatrix obj = new MyMatrix();
		int[,] matrix = {
			{
				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 , 26 , 27 , 28 , 29 , 30
			} , {
				31 , 32 , 33 , 34 , 35 , 36
			}
		};
		int size = matrix.GetLength(0);
		Console.Write("\n Before rotate \n");
		obj.show_data(matrix, size);
		obj.rotate_90_degree(matrix, size);
		Console.Write("\n After rotate \n");
		obj.show_data(matrix, size);
	}
}

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
<?php
/*
    Php Program 
    Inplace rotate square matrix by 90 degrees
*/
class MyMatrix
{
	// Rotate the square matrix element in 90 degrees
	public	function rotate_90_degree( & $matrix, $size)
	{
		// Define loop control variables
		$i = 1;
		$j = 0;
		$temp = 0;
		/*
		        Diagonal transform the elements of upper triangular matrix
		        Example
		        ----------------------------

		            /  /  / 
		           /  /      Upper Triangular
		          /
		        ----------------------------

		          1   2   3
		          4   5      Element Like this
		          6
		        -----------------------------


		          1   4   6
		          2   5       After transform
		          3
		        --------------------------------

		        */
		for ($i = 1; $i < $size; ++$i)
		{
			$j = 0;
			while ($j < $i)
			{
				$temp = $matrix[$j][$i - $j];
				$matrix[$j][$i - $j] = $matrix[$i - $j][$j];
				$matrix[$i - $j][$j] = $temp;
				$j++;
			}
		}
		/*
		        // Diagonal transform the elements of lower triangular matrix
		        // Example
		        ---------------------------
		            /
		           /  /  
		          /  /  /   Lower Triangular
		          ---------------------------

		                1   
		             2  3   Element Like this
		          4  5  6 
		         
		          ------------------------------ 

		                4  
		             2  5   After transform
		          1  3  6 
		          ------------------------------  

		        */
		for ($i = 1; $i < $size - 1; ++$i)
		{
			$j = 0;
			while ($j < $i)
			{
				$temp = $matrix[$i - $j][($size - 1) - $j];
				$matrix[$i - $j][($size - 1) - $j] = $matrix[($size - 1) - $j][$i - $j];
				$matrix[($size - 1) - $j][$i - $j] = $temp;
				$j++;
			}
		}
		/*
		        Invert column values

		            |  |  |  |
		            |  |  |  |  pattern
		            |  |  |  |
		            |  |  |  |
		         
		            -------

		            1   5   9   13
		            2   6   10  14  Element Like this
		            3   7   11  15
		            4   9   12  16
		            -------------  

		            4   9   12  16
		            3   7   11  15  After transform
		            2   6   10  14
		            1   5   9   13
		            -------------  

		        */
		for ($i = 0; $i < $size; ++$i)
		{
			for ($j = 0; $j < intval($size / 2); ++$j)
			{
				$temp = $matrix[$j][$i];
				$matrix[$j][$i] = $matrix[($size - 1) - $j][$i];
				$matrix[($size - 1) - $j][$i] = $temp;
			}
		}
	}
	// Display matrix elements
	public	function show_data( & $matrix, $size)
	{
		$i = 0;
		$j = 0;
		for ($i = 0; $i < $size; ++$i)
		{
			for ($j = 0; $j < $size; ++$j)
			{
				echo "  ". $matrix[$i][$j];
			}
			echo "\n";
		}
		echo "\n";
	}
}

function main()
{
	$obj = new MyMatrix();
	$matrix = array(
      array(1, 2, 3, 4, 5, 6), 
      array(7, 8, 9, 10, 11, 12), 
      array(13, 14, 15, 16, 17, 18), 
      array(19, 20, 21, 22, 23, 24), 
      array(25, 26, 27, 28, 29, 30), 
      array(31, 32, 33, 34, 35, 36));
	$size = count($matrix[0]);
	echo "\n Before rotate \n";
	$obj->show_data($matrix, $size);
	$obj->rotate_90_degree($matrix, $size);
	echo "\n After rotate \n";
	$obj->show_data($matrix, $size);
}
main();

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
/*
    Node Js Program 
    Inplace rotate square matrix by 90 degrees
*/
class MyMatrix
{
	// Rotate the square matrix element in 90 degrees
	rotate_90_degree(matrix, size)
	{
		// Define loop control variables
		var i = 1;
		var j = 0;
		var temp = 0;
		/*
		        Diagonal transform the elements of upper triangular matrix
		        Example
		        ----------------------------

		            /  /  / 
		           /  /      Upper Triangular
		          /
		        ----------------------------

		          1   2   3
		          4   5      Element Like this
		          6
		        -----------------------------


		          1   4   6
		          2   5       After transform
		          3
		        --------------------------------

		        */
		for (i = 1; i < size; ++i)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[j][i - j];
				matrix[j][i - j] = matrix[i - j][j];
				matrix[i - j][j] = temp;
				j++;
			}
		}
		/*
		        // Diagonal transform the elements of lower triangular matrix
		        // Example
		        ---------------------------
		            /
		           /  /  
		          /  /  /   Lower Triangular
		          ---------------------------

		                1   
		             2  3   Element Like this
		          4  5  6 
		         
		          ------------------------------ 

		                4  
		             2  5   After transform
		          1  3  6 
		          ------------------------------  

		        */
		for (i = 1; i < size - 1; ++i)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[i - j][(size - 1) - j];
				matrix[i - j][(size - 1) - j] = matrix[(size - 1) - j][i - j];
				matrix[(size - 1) - j][i - j] = temp;
				j++;
			}
		}
		/*
		        Invert column values

		            |  |  |  |
		            |  |  |  |  pattern
		            |  |  |  |
		            |  |  |  |
		         
		            -------

		            1   5   9   13
		            2   6   10  14  Element Like this
		            3   7   11  15
		            4   9   12  16
		            -------------  

		            4   9   12  16
		            3   7   11  15  After transform
		            2   6   10  14
		            1   5   9   13
		            -------------  

		        */
		for (i = 0; i < size; ++i)
		{
			for (j = 0; j < parseInt(size / 2); ++j)
			{
				temp = matrix[j][i];
				matrix[j][i] = matrix[(size - 1) - j][i];
				matrix[(size - 1) - j][i] = temp;
			}
		}
	}
	// Display matrix elements
	show_data(matrix, size)
	{
		var i = 0;
		var j = 0;
		for (i = 0; i < size; ++i)
		{
			for (j = 0; j < size; ++j)
			{
				process.stdout.write("  " + matrix[i][j]);
			}
			process.stdout.write("\n");
		}
		process.stdout.write("\n");
	}
}

function main()
{
	var obj = new MyMatrix();
	var matrix = [
		[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, 26, 27, 28, 29, 30] , 
        [31, 32, 33, 34, 35, 36]
	];
	var size = matrix[0].length;
	process.stdout.write("\n Before rotate \n");
	obj.show_data(matrix, size);
	obj.rotate_90_degree(matrix, size);
	process.stdout.write("\n After rotate \n");
	obj.show_data(matrix, size);
}
main();

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
#  Python 3 Program 
#  Inplace rotate square matrix by 90 degrees

class MyMatrix :
	#  Rotate the square matrix element in 90 degrees
	def rotate_90_degree(self, matrix, size) :
		#  Define loop control variables
		i = 1
		j = 0
		temp = 0
		# 
		#        Diagonal transform the elements of upper triangular matrix
		#        Example
		#        ----------------------------
		#            /  /  / 
		#           /  /      Upper Triangular
		#          /
		#        ----------------------------
		#          1   2   3
		#          4   5      Element Like this
		#          6
		#        -----------------------------
		#          1   4   6
		#          2   5       After transform
		#          3
		#        --------------------------------
		#         
		
		i = 1
		while (i < size) :
			j = 0
			while (j < i) :
				temp = matrix[j][i - j]
				matrix[j][i - j] = matrix[i - j][j]
				matrix[i - j][j] = temp
				j += 1
			
			i += 1
		
		# 
		#         Diagonal transform the elements of lower triangular matrix
		#         Example
		#         ---------------------------
		#             /
		#            /  /  
		#           /  /  /   Lower Triangular
		#           ---------------------------
		#                 1   
		#              2  3   Element Like this
		#           4  5  6 
		#          
		#           ------------------------------ 
		#                 4  
		#              2  5   After transform
		#           1  3  6 
		#           ------------------------------  
		#         
		
		i = 1
		while (i < size - 1) :
			j = 0
			while (j < i) :
				temp = matrix[i - j][(size - 1) - j]
				matrix[i - j][(size - 1) - j] = matrix[(size - 1) - j][i - j]
				matrix[(size - 1) - j][i - j] = temp
				j += 1
			
			i += 1
		
		# 
		#         Invert column values
		#             |  |  |  |
		#             |  |  |  |  pattern
		#             |  |  |  |
		#             |  |  |  |
		#          
		#             -------
		#             1   5   9   13
		#             2   6   10  14  Element Like this
		#             3   7   11  15
		#             4   9   12  16
		#             -------------  
		#             4   9   12  16
		#             3   7   11  15  After transform
		#             2   6   10  14
		#             1   5   9   13
		#             -------------  
		#         
		
		i = 0
		while (i < size) :
			j = 0
			while (j < int(size / 2)) :
				temp = matrix[j][i]
				matrix[j][i] = matrix[(size - 1) - j][i]
				matrix[(size - 1) - j][i] = temp
				j += 1
			
			i += 1
		
	
	#  Display matrix elements
	def show_data(self, matrix, size) :
		i = 0
		j = 0
		i = 0
		while (i < size) :
			j = 0
			while (j < size) :
				print("  ", matrix[i][j], end = "")
				j += 1
			
			print("\n", end = "")
			i += 1
		
		print("\n", end = "")
	

def main() :
	obj = MyMatrix()
	matrix = [
		[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, 26, 27, 28, 29, 30] , 
        [31, 32, 33, 34, 35, 36]
	]
	size = len(matrix[0])
	print("\n Before rotate \n", end = "")
	obj.show_data(matrix, size)
	obj.rotate_90_degree(matrix, size)
	print("\n After rotate \n", end = "")
	obj.show_data(matrix, size)

if __name__ == "__main__": main()

Output

 Before rotate
   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   26   27   28   29   30
   31   32   33   34   35   36


 After rotate
   6   12   18   24   30   36
   5   11   17   23   29   35
   4   10   16   22   28   34
   3   9   15   21   27   33
   2   8   14   20   26   32
   1   7   13   19   25   31
# 
#     Ruby Program 
#     Inplace rotate square matrix by 90 degrees

class MyMatrix 
	#  Rotate the square matrix element in 90 degrees
	def rotate_90_degree(matrix, size) 
		#  Define loop control variables
		i = 1
		j = 0
		temp = 0
		# 
		#        Diagonal transform the elements of upper triangular matrix
		#        Example
		#        ----------------------------
		#            /  /  / 
		#           /  /      Upper Triangular
		#          /
		#        ----------------------------
		#          1   2   3
		#          4   5      Element Like this
		#          6
		#        -----------------------------
		#          1   4   6
		#          2   5       After transform
		#          3
		#        --------------------------------
		#         
		
		i = 1
		while (i < size) 
			j = 0
			while (j < i) 
				temp = matrix[j][i - j]
				matrix[j][i - j] = matrix[i - j][j]
				matrix[i - j][j] = temp
				j += 1
			end

			i += 1
		end

		# 
		#         // Diagonal transform the elements of lower triangular matrix
		#         // Example
		#         ---------------------------
		#             /
		#            /  /  
		#           /  /  /   Lower Triangular
		#           ---------------------------
		#                 1   
		#              2  3   Element Like this
		#           4  5  6 
		#          
		#           ------------------------------ 
		#                 4  
		#              2  5   After transform
		#           1  3  6 
		#           ------------------------------  
		#         
		
		i = 1
		while (i < size - 1) 
			j = 0
			while (j < i) 
				temp = matrix[i - j][(size - 1) - j]
				matrix[i - j][(size - 1) - j] = matrix[(size - 1) - j][i - j]
				matrix[(size - 1) - j][i - j] = temp
				j += 1
			end

			i += 1
		end

		# 
		#         Invert column values
		#             |  |  |  |
		#             |  |  |  |  pattern
		#             |  |  |  |
		#             |  |  |  |
		#          
		#             -------
		#             1   5   9   13
		#             2   6   10  14  Element Like this
		#             3   7   11  15
		#             4   9   12  16
		#             -------------  
		#             4   9   12  16
		#             3   7   11  15  After transform
		#             2   6   10  14
		#             1   5   9   13
		#             -------------  
		#         
		
		i = 0
		while (i < size) 
			j = 0
			while (j < size / 2) 
				temp = matrix[j][i]
				matrix[j][i] = matrix[(size - 1) - j][i]
				matrix[(size - 1) - j][i] = temp
				j += 1
			end

			i += 1
		end

	end

	#  Display matrix elements
	def show_data(matrix, size) 
		i = 0
		j = 0
		i = 0
		while (i < size) 
			j = 0
			while (j < size) 
				print("  ", matrix[i][j])
				j += 1
			end

			print("\n")
			i += 1
		end

		print("\n")
	end

end

def main() 
	obj = MyMatrix.new()
	matrix = [
		[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, 26, 27, 28, 29, 30] ,
        [31, 32, 33, 34, 35, 36]
	]
	size = matrix[0].length
	print("\n Before rotate \n")
	obj.show_data(matrix, size)
	obj.rotate_90_degree(matrix, size)
	print("\n After rotate \n")
	obj.show_data(matrix, size)
end

main()

Output

 Before rotate 
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate 
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31

/*
    Scala Program 
    Inplace rotate square matrix by 90 degrees
*/
class MyMatrix
{
	//  Rotate the square matrix element in 90 degrees
	def rotate_90_degree(matrix: Array[Array[Int]], size: Int): Unit = {
		//  Define loop control variables
		var i: Int = 1;
		var j: Int = 0;
		var temp: Int = 0;
		/*
		       Diagonal transform the elements of upper triangular matrix
		       Example
		       ----------------------------

		           /  /  / 
		          /  /      Upper Triangular
		         /
		       ----------------------------

		         1   2   3
		         4   5      Element Like this
		         6
		       -----------------------------


		         1   4   6
		         2   5       After transform
		         3
		       --------------------------------

		        */
		i = 1;
		while (i < size)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix(j)(i - j);
				matrix(j)(i - j) = matrix(i - j)(j);
				matrix(i - j)(j) = temp;
				j += 1;
			}
			i += 1;
		}
		/*
		        // Diagonal transform the elements of lower triangular matrix
		        // Example
		        ---------------------------
		            /
		           /  /  
		          /  /  /   Lower Triangular
		          ---------------------------

		                1   
		             2  3   Element Like this
		          4  5  6 
		         
		          ------------------------------ 

		                4  
		             2  5   After transform
		          1  3  6 
		          ------------------------------  

		        */
		i = 1;
		while (i < size - 1)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix(i - j)((size - 1) - j);
				matrix(i - j)((size - 1) - j) = matrix((size - 1) - j)(i - j);
				matrix((size - 1) - j)(i - j) = temp;
				j += 1;
			}
			i += 1;
		}
		/*
		        Invert column values

		            |  |  |  |
		            |  |  |  |  pattern
		            |  |  |  |
		            |  |  |  |
		         
		            -------

		            1   5   9   13
		            2   6   10  14  Element Like this
		            3   7   11  15
		            4   9   12  16
		            -------------  

		            4   9   12  16
		            3   7   11  15  After transform
		            2   6   10  14
		            1   5   9   13
		            -------------  

		        */
		i = 0;
		while (i < size)
		{
			j = 0;
			while (j < (size / 2).toInt)
			{
				temp = matrix(j)(i);
				matrix(j)(i) = matrix((size - 1) - j)(i);
				matrix((size - 1) - j)(i) = temp;
				j += 1;
			}
			i += 1;
		}
	}
	//  Display matrix elements
	def show_data(matrix: Array[Array[Int]], size: Int): Unit = {
		var i: Int = 0;
		var j: Int = 0;
		i = 0;
		while (i < size)
		{
			j = 0;
			while (j < size)
			{
				print("  " + matrix(i)(j));
				j += 1;
			}
			print("\n");
			i += 1;
		}
		print("\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: MyMatrix = new MyMatrix();
		var matrix: Array[Array[Int]] = Array(
          Array(1, 2, 3, 4, 5, 6), 
          Array(7, 8, 9, 10, 11, 12), 
          Array(13, 14, 15, 16, 17, 18), 
          Array(19, 20, 21, 22, 23, 24), 
          Array(25, 26, 27, 28, 29, 30),
          Array(31, 32, 33, 34, 35, 36)
        );
		var size: Int = matrix(0).length;
		print("\n Before rotate \n");
		obj.show_data(matrix, size);
		obj.rotate_90_degree(matrix, size);
		print("\n After rotate \n");
		obj.show_data(matrix, size);
	}
}

Output

 Before rotate
  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  26  27  28  29  30
  31  32  33  34  35  36


 After rotate
  6  12  18  24  30  36
  5  11  17  23  29  35
  4  10  16  22  28  34
  3  9  15  21  27  33
  2  8  14  20  26  32
  1  7  13  19  25  31
/*
    Swift 4 Program 
    Inplace rotate square matrix by 90 degrees
*/
class MyMatrix
{
	//  Rotate the square matrix element in 90 degrees
	func rotate_90_degree(_ matrix: inout[[Int]], _ size: Int)
	{
		//  Define loop control variables
		var i: Int = 1;
		var j: Int = 0;
		var temp: Int = 0;
		/*
		      Diagonal transform the elements of upper triangular matrix
		      Example
		      ----------------------------

		          /  /  / 
		         /  /      Upper Triangular
		        /
		      ----------------------------

		        1   2   3
		        4   5      Element Like this
		        6
		      -----------------------------


		        1   4   6
		        2   5       After transform
		        3
		      --------------------------------

		       */
		i = 1;
		while (i < size)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[j][i - j];
				matrix[j][i - j] = matrix[i - j][j];
				matrix[i - j][j] = temp;
				j += 1;
			}
			i += 1;
		}
		/*
		       // Diagonal transform the elements of lower triangular matrix
		       // Example
		       ---------------------------
		           /
		          /  /  
		         /  /  /   Lower Triangular
		         ---------------------------

		               1   
		            2  3   Element Like this
		         4  5  6 
		        
		         ------------------------------ 

		               4  
		            2  5   After transform
		         1  3  6 
		         ------------------------------  

		       */
		i = 1;
		while (i < size - 1)
		{
			j = 0;
			while (j < i)
			{
				temp = matrix[i - j][(size - 1) - j];
				matrix[i - j][(size - 1) - j] = matrix[(size - 1) - j][i - j];
				matrix[(size - 1) - j][i - j] = temp;
				j += 1;
			}
			i += 1;
		}
		/*
		       Invert column values

		           |  |  |  |
		           |  |  |  |  pattern
		           |  |  |  |
		           |  |  |  |
		        
		           -------

		           1   5   9   13
		           2   6   10  14  Element Like this
		           3   7   11  15
		           4   9   12  16
		           -------------  

		           4   9   12  16
		           3   7   11  15  After transform
		           2   6   10  14
		           1   5   9   13
		           -------------  

		       */
		i = 0;
		while (i < size)
		{
			j = 0;
			while (j < size / 2)
			{
				temp = matrix[j][i];
				matrix[j][i] = matrix[(size - 1) - j][i];
				matrix[(size - 1) - j][i] = temp;
				j += 1;
			}
			i += 1;
		}
	}
	//  Display matrix elements
	func show_data(_ matrix: [[Int]], _ size: Int)
	{
		var i: Int = 0;
		var j: Int = 0;
		i = 0;
		while (i < size)
		{
			j = 0;
			while (j < size)
			{
				print("  ", matrix[i][j], terminator: "");
				j += 1;
			}
			print("\n", terminator: "");
			i += 1;
		}
		print("\n", terminator: "");
	}
}
func main()
{
	let obj: MyMatrix = MyMatrix();
	var matrix: [[Int]] = [
		[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, 26, 27, 28, 29, 30] , 
        [31, 32, 33, 34, 35, 36]
	];
	let size: Int = matrix[0].count;
	print("\n Before rotate \n", terminator: "");
	obj.show_data(matrix, size);
	obj.rotate_90_degree(&matrix, size);
	print("\n After rotate \n", terminator: "");
	obj.show_data(matrix, size);
}
main();

Output

 Before rotate
   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   26   27   28   29   30
   31   32   33   34   35   36


 After rotate
   6   12   18   24   30   36
   5   11   17   23   29   35
   4   10   16   22   28   34
   3   9   15   21   27   33
   2   8   14   20   26   32
   1   7   13   19   25   31

Output Explanation

The given Java code implements the above algorithm to rotate the matrix by 90 degrees clockwise in place. It prints the original matrix, performs the rotation, and then prints the rotated matrix.

Time Complexity

The time complexity of the provided solution is O(N^2), where N is the size of the square matrix. The function performs two operations: transposing the matrix and reversing each row. Both operations require iterating through the elements of the matrix at least once. Therefore, the overall time complexity is O(N^2).

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment