×

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by 90 degrees in Java. The anti-clockwise rotations of the matrix is also referred as the left rotation of a matrix, while the clockwise rotation is indeed referred to as the right rotation of that same matrix.

What is a Matrix in Java?

Technically referring, a matrix is a rectangular, two-dimensional array that contains either integers, symbols, or statements as its fundamental elements. The elements in the matrix are arranged in rows and columns.

For an instance, m x n matrix refers to a matrix containing 'm' number of rows and 'n' number of columns. 'a [i][j]', which denotes that the element an is represented in the i-th row and j-th column, can be used to represent individual values in the matrix, which are referred to as elements.

Look at the example below to understand how a matrix actually looks like

Example:

                              a[][]= { 12, 5, 0,

                                    11, 7, 6,

                                    10, 8, 15}

The above example is a matrix or it can also be termed as two-dimensional array, with 3 rows and 3 columns. The representation of the above matrix elements in Z form shall certainly include the entire first row of the matrix, the right diagonal and the entire last row of the matrix too.

Now let us discuss about how to rotate a given matrix by 90 degrees in clockwise direction and also in anti-clockwise direction.

Let us first look at how a matrix can be rotated in clockwise rotation or simply right rotation.

Rotating matrix 90 degrees in clockwise direction.

Rotating a matrix 90 degrees in clockwise direction is process which can be accomplished by implementing two steps. The two steps are:

  • Initially, determine the matrix's transpose.
  • Unless the matrix is 3x3, swap the entries in the initial column with those in the last column. The second column does not change.

Note: The number of columns and rows in a matrix must and should be same. Then only the rotation of any matrix in any direction would be possible.

Look at the example below to understand how the rotation works.

{[1 ,2 ,3]

  [4 ,5 ,6]

  [7 ,8 ,9]}

Let us find the transpose of the above matrix.

{[1 ,4 ,7]

[2 ,5 ,8]

[3 ,6 ,9]}

Now lets us swap the first column and the last column.

{[7 ,4 ,1]

[8 ,5 ,2]

[9 ,6 ,3]}

The above matrix after rotating 90 degrees in clockwise direction. Lets us go through a simple example program.

File name: Clockwise.java

public class Clockwise  
{  
//method to rotate the matrix 90 degrees in clockwise direction  
static void rotateRight(int matrix[][],int n)  
{  
//to find out the transpose of the matrix  
for(int i=0;i<n;i++)  
{  
for(int j=i;j<n;j++)  
{  
int temp = matrix[i][j];  
matrix[i][j] = matrix[j][i];  
matrix[j][i] = temp;  
}  
}  
  
//reversing the elements of each row 
for(int i=0;i<n;i++)  
{      
int low = 0, high = n-1;  
while(low < high)  
{  
int temp = matrix[i][low];  
matrix[i][low] = matrix[i][high];  
matrix[i][high] = temp;  
low++;  
high--;  
}  
}  
  
System.out.println("The matrix after rotating 90 degrees in clockwise direction: ");    
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
System.out.print(matrix[i][j]+" " +"\t");  
}  
System.out.println();  
}  
}
public static void main(String args[])  
{  
int n=3;  
// creating a matrix
int matrix[][] = new int[][]{ {1,2,3}, {4,5,6} , {7,8,9} };  
System.out.println("The matrix before rotating 90 degrees in clockwise direction: ");  
// displays the matrix
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
//displays the elements of the matrix     
System.out.print(matrix[i][j]+" " +"\t");  
}  
System.out.println();  
}  
//invoking the method
rotateRight(matrix, n);  
}  
}   

Output

The matrix before rotating 90 degrees in clockwise direction:
1       2       3
4       5       6
7       8       9
The matrix after rotating 90 degrees in clockwise direction:
7       4       1
8       5       2
9       6       3

Rotating matrix 90 degrees in anti-clockwise direction

File name: Anticlockwise.java

public class Anticlockwise
{  
//method to rotate the matrix 90 degrees in anti-clockwise direction  
static void rotateLeft(int matrix[][], int n)  
{  
//finding the transpose of the matrix
for(int i=0;i<n;i++)  
{  
for(int j=i;j<n;j++)  
{  
int temp = matrix[i][j];  
matrix[i][j] = matrix[j][i];  
matrix[j][i] = temp;  
}  
}  
for(int i=0;i<n;i++)  
{   
int low = 0;  
int high = n-1;  
while(low < high)  
{  
int temp = matrix[low][i];  
matrix[low][i] = matrix[high][i];  
matrix[high][i] = temp;  
low++;  
high--;  
}  
}  
//displays the matrix after the rotation   
System.out.println("The matrix after rotating in in anti-clockwise direction: ");  
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
System.out.print(matrix[i][j]+" "+"\t");  
}  
System.out.println();  
}  
}  
public static void main(String args[])  
{    
int n=3;  
//creating a matrix 
int matrix[][] = new int[][]{ {1,2,3}, {4,5,6} , {7,8,9} };  
//displays the matrix  
System.out.println("The matrix before rotating 90 degrees in anti-clockwise direction: ");  
for(int i=0;i<3;i++)  
{
for(int j=0;j<3;j++)  
{  
//displays elements of the matrix       
System.out.print(matrix[i][j]+" "+"\t");  
}  
System.out.println();  
}     
rotateLeft(matrix,n);  
}  
}  

Output:

The matrix before rotating 90 degrees in anti-clockwise direction:
1       2       3
4       5       6
7       8       9
The matrix after rotating in in anti-clockwise direction:
3       6       9
2       5       8
1       4       7

Related Topics

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.