Rotate Image - The Coding Shala
In this post, we will learn how to Rotate an Image or in other words how to Rotate a Matrix. We will implement Rotate Image Java Solution.
Rotate Image Problem
Rotate Image Java Solution
Using extra space. We can do this easily by using extra matrix.
Java Program:
int[][] rotateImage(int[][] a) { int len = a.length; int[][] ans = new int[len][len]; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ ans[j][len-i-1] = a[i][j]; } } return ans; }
Without using extra space.
Here is a common method to solve image rotation problems.
For clockwise rotation
Step 1: First we reverse up to down array rows that means the first row becomes the last row and the second row becomes the second the last row and so on.
Step 2: Swap the elements in the symmetry.
Example:
4 5 6 => 4 5 6 => 8 5 2
7 8 9 1 2 3 9 6 3
For AntiClockwise rotation
Step 1: First we reverse the array left to right that means first column become last column and second column become secont last column and so on.
Step 2: Swap the elements in the symmetry.
Example:
Java Program for Clockwise Image Rotation:
class Solution { public void rotate(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; for(int i=0;i<row/2;i++){ for(int j=0;j<col;j++){ int tmp = matrix[i][j]; matrix[i][j] = matrix[row-i-1][j]; matrix[row-i-1][j] = tmp; } } for(int i=0;i<row;i++){ for(int j=i+1;j<col;++j){ int tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } } }
- Spiral Order Matrix 1
- Anti Diagonals
- Diagonal Traverse
- How to Check if Given Sudoku is Valid or not
- Detect Cycle in Linked List
Comments
Post a Comment