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 in place?
void rotate90Degrees(byte[][] image) { // Run through rows 0 -> n/2 - 1 and rotate all bytes in that row for (int i = 0; i < n/2; i++) { for (int j = i; j < n - i; j++) { rotateByte90Degrees(image, i, j); } } } // Rotate all four bytes corresponding to x,y. void rotateByte90Degrees(byte[][] image, int x, int y) { int lastIndex = image.length - 1; byte nextByte = image[y][lastIndex - x]; // Rotation 1 image[y][lastIndex - x] = image[x][y]; // Store the byte that was overwritten in x,y. // We are treating image[x][y] as an additional temp var. image[x][y] = nextByte; // Store the next byte that will be overwritten nextByte = image[lastIndex - x][lastIndex - y]; // Rotation 2 image[lastIndex - x][lastIndex - y] = image[x][y]; image[x][y] = nextByte; nextByte = image[lastIndex - y][x]; // Rotation 3 image[lastIndex - y][x] = image[x][y]; // Rotation 4 image[x][y] = nextByte; }
No comments:
Post a Comment