Wednesday, January 1, 2014

Matrix Related Questions


  1. Question:
    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?

    Answer: idea from this post, I feel it's easier to understand than the layer switch approach on the book. Depending on whether it's clock-wise/counter clock-wise rotation, we first switch the elements along the main diagonal/reverse diagonal and switch row i with row n-i.


    // counter-clockwise rotate: switch elements along main diagonal
        public static void rotateCounterClock(int[][] matrix, int n) {
            // only mirror switch elements on upper, right triangle
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    int tmp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = tmp;
                }
            }
    
            for (int i = 0; i < n / 2; i++) {
                for (int j = 0; j < n; j++) {
                    int tmp = matrix[i][j];
                    matrix[i][j] = matrix[n - 1 - i][j];
                    matrix[n - 1 - i][j] = tmp;
                }
            }
        }
    
        // clockwise rotate: switch elements along reverse diagonal
        public static void rotateClock(int[][] matrix, int n) {
            // only switch the elements in the upper left triangle
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n - 1 - i; j++) {
                    int tmp = matrix[i][j];
                    matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                    matrix[n - 1 - j][n - 1 - i] = tmp;
                }
            }
    
            for (int i = 0; i < n / 2; i++) {
                for (int j = 0; j < n; j++) {
                    int tmp = matrix[i][j];
                    matrix[i][j] = matrix[n - 1 - i][j];
                    matrix[n - 1 - i][j] = tmp;
                }
            }
        }
    

  2. Question: TEMPLATE QuestionLink


    Answer:

No comments:

Post a Comment