# Coding Challenge Day-4: Problem 3: Rotate Image(matrix) by 90 degrees

Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 4: Problem 3! Be sure to post your answers, queries etc in the comments!!

Problem: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes. Write a method to rotate the image by 90 degrees. Can you do this inplace?

Sample: original matrix: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Ouput: 4 8 12 16 (rotated by 90 degrees in anti-clockwise direction)
3 7 11 15
2 6 10 14
1 5 9 13

Solution:

``````package array;

public class Program003rotate_image {

public static void rotate_image(int [][] image, int N){

for(int i=0; i<N/2; i++){
for(int j=i; j<(N-i-1); j++){
int temp= image[i][j];
image[i][j]= image[j][N-i-1];
image[j][N-i-1]= image[N-i-1][N-j-1];
image[N-i-1][N-j-1]= image[N-j-1][i];
image[N-j-1][i]= temp;
}
}
}

public static void display_image (int [][] image, int N){
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
System.out.printf(" %2d ",image[i][j]);
}
System.out.println();
}
}

public static void main ( String [] args){
int image[][]= {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
rotate_image(image, 4);
display_image (image,4);

}

}
``````

Refernces:
1. Cracking the Coding Interview (by Gayle Laakmann McDowell)

Happy learning!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.