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 in place?

public class MatrixRotation {

//we have a n*n matrix
 public static void rotate(int[][] matrix, int n){

 int layer = n/2;

 for(int i = 0; i < layer; i++){
 int end = n - i - 2;

 for(int j = i; j <= end; j++){
 int temp = matrix[i][j];
 matrix[i][j] = matrix[n - 1 - j][i];
 matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
 matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
 matrix[j][n - 1 - i] = temp;
 }
 }
 }

}

Advertisements

One thought on “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 in place?

  1. […] Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a metho… […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s