Как повернуть массив на 90 градусов java

от admin

How do I rotate a matrix 90 degrees counterclockwise in java? [duplicate]

I’m trying to go over the problems in the Cracking the Coding Interview book. One of the questions asks me to rotate a matrix 90 degrees clockwise. Now, while trying to solidify my understanding of matrix rotation, I tried to embark on a new problem: to try to rotate a matrix 90 degrees counterclockwise (the other direction).

I’ve tried to go through layers of a square matrix, the outer layer, iterating all the way into the inner layer and rotating all the indexes of each side of the "square" one by one. This basically is what Gayle Laakman McDowell’s solution implemented, but the other direction.

Name already in use

Lessons / chapter_001 / src / main / java / ru / job4j / array / RotateArray.java /

  • Go to file T
  • Go to line L
  • Go to definition R
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Rotate matrix by 90 degree

Rotate matrix by 90 degree OR
Turn an 2D array by 90 degree OR
Rotate a two dimensional array OR
Given N*M matrix, rotate it by 90 degree to left and right.
Given N*M Matrix, Rotate it by 90 degrees .

Lets understand the problem statement graphically and it will be more clear,

Algorithm

  1. In Place.
  2. Using extra Memory .

We already saw how to Rotate a Matrix In — Place: Rotate Matrix to 90 degrees Inplace .

In this post, we will focus on Rotating a Matrix by 90 degrees clockwise using Extra memory .

For Rotating a matrix to 90 degrees clockwise, We need to transform each row of a Matrix to a column in rotated matrix. ( Check the rotated matrix image above )

It is very easy to solve this problem if it is well understood.

What will be Rows and Columns of Rotated Result Matrix?
For rotating matrix to 90 degrees, we need to transform rows into columns and columns to rows in a result matrix. So number of rows in rotated matrix will be equal to number of columns of original matrix and number of columns in rotated matrix will be equal to number of rows.

Rotate Matrix by 90 degrees in java

Rotate matrix by 90 degrees in java

In this article, we will look into another interesting problem related to 2D Arrays. Given a Matrix of N X N Dimension we have to Rotate matrix by 90 degrees. We will perform Rotation both Clockwise i.e. Right Rotation and Anti-Clockwise i.e. Left Rotation respectively. We will discuss each operation in detail along with a hint to perform Rotation of Matrix K times .

Note: To Perform Any type of Rotation, The Matrix should have equal dimensions (N X N) i.e. No. of Rows in Matrix = No. of Columns in Matrix.

Table of Contents

Clockwise or Right Rotate a Matrix

In this type, we need to Right Rotate the given N X N Matrix by 90 degrees. Let us understand this with an example:

Basically, we need to start from the last row in the Original Matrix and need to make each row as a column to rotate the matrix in Clockwise direction.

So, let us look at the approach to do this :

  • We will first transpose of given matrix or 2D Array. By Transpose, we mean each Row of the matrix becomes a Column and vice-versa. In simple words, each Element in i th row is replaced by corresponding element in the i th column. We will do this in code by Swapping the elements at the i th row and column respectively. So, considering the above matrix the Transpose will be:

  • After doing transpose, we need to just reverse the contents/elements of each row. Since each Row of the matrix is a 1D Array itself, we just reverse each array or row after that we would have the Right Rotated Matrix. So after reversing the Transpose Matrix we get the result.

Implementation in Java

Now, let us look at the code to cover this approach considering the same example as discussed above.

Time Complexity: The time complexity of performing rotation is O(n 2 ) as we traverse all the elements of the matrix while interchanging them.

Further reading:

Matrix multiplication in java
Find transpose of matrix in java

Anti-Clockwise or Left Rotate a Matrix

In this type, we need to Left Rotate the given N X N Matrix by 90 degrees. Let us understand this with an example:

Basically, we need to start from the last row in the Original Matrix and need to make each column as a row to rotate the matrix in anti clockwise direction.

So, let us look at the approach to do this :

  • Like the approach we followed above in Right Rotate, we will first transpose the given Matrix or 2D Array. We convert elements of each Row of the matrix becomes a Column and vice-versa. So, considering the above matrix the Transpose will be:

  • After getting the transpose, Instead of reversing the Rows like we did in Right Rotate, Here we reverse contents of each Column in the Matrix. After doing this, we will have our resultant Left Rotated Matrix:

Now let us look at the implementation in code:

Time Complexity: The time complexity for this type is also O(n 2 ) .

How to Rotate Matrix K Times?

Now if we want to Rotate a matrix K times, Depending on the type of rotation just call the rightRotate() or leftRotate() method inside a loop K times and print the matrix once like this:

So that’s all about how to Rotate Matrix by 90 degrees in java. You can try out the code with different examples and let us know your queries.

Was this post helpful?

Share this

Data Structures in java

Related Posts

Author

Related Posts

Data structures in java

Data Structures in java

Table of ContentsArray Declare and initialize array in javaAdvantages of arrayDisadvantages of array ExampleArray practice programsStackStack implementation using ArrayStack implementation using LinkedListImplementationPractice ProgramsQueueQueue implementation using arrayQueue implementation using LinkedListImplementationLinkedListImplementationLinkedList Practice ProgramsBinary treeImplementationBinary tree practice programsBinary Search treeImplementationBinary search tree Practice programsTrieImplementationHeapImplementationGraphImplementation Inbuild data structures in javaStringHashMapLinkedHashMapArrayListLinkedListHashSet In this post, we will see about various data […]

Top 100+ Java coding interview questions

Table of ContentsStringQuestion 1 : How to reverse a String in java? Can you write a program without using any java inbuilt methods?Question 2 : Write a java program to check if two Strings are anagram in java?Question 3 : Write a program to check if String has all unique characters in java?Question 4 : […]

Minimum Number of Jumps to reach last Index

Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see how to find Minimum Number of Jumps to reach last Index. Problem Given an array A of positive integers possibly zeroes, every index indicating the maximum length of a […]

Inorder Successor in a Binary Search Tree

Table of ContentsProblemSolutionAPPROACH – I :Approach – II:(i) If the target node has a right child :(ii) If the target node does not have a right child :Time Complexity Discussion If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see how to […]

LCA of a K-ary Tree in O(Sqrt(height))

Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see about how to find Lowest Common Ancestor of a K-ary Tree in O(Sqrt(height)).We have already seen how to find LCA of n-ary tree in O(n) complexity. Problem Given a […]

Largest Rectangular Area in a Histogram

Table of ContentsProblemSolutionAPPROACH – IAPPROACH – II (RECURSIVE):Approach – III (ITERATIVE) : If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see about how to find largest rectangular area in a Histogram. Problem Given an Integer representing number of bars in a […]

Читать:
Map entry java что это

Related Posts