Sunday, November 6, 2011

Interview Problem: Rotate Matrix.

Problem

Rotate the Matrix by 90 degree.

Solution:


/**
 * 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.
 */
/**
 * @author antonio081014
 * @since Nov 6, 2011, 4:57:14 PM
 */
public class MatrixRotation {

    public static void rotate(int[][] matrix, int n) {
        for (int i = 0; i < n / 2; i++) {
            int left = i;
            int right = n - 1 - i;
            for (int j = left; j < right; j++) {
                int offset = j - left;
                // save the top element;
                int tmp = matrix[left][left + offset];
                // right -> top;
                matrix[left][left + offset] = matrix[left + offset][right];
                // bottom -> right;
                matrix[left + offset][right] = matrix[right][right - offset];
                // left -> bottom;
                matrix[right][right - offset] = matrix[right - offset][left];
                // top -> left;
                matrix[right - offset][left] = tmp;
            }
        }
    }
}

No comments :