Rotate Image

Description

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up: Could you do this in-place?

Hide Company Tags Amazon Microsoft Apple

Hide Tags Array

Thinking
  • rotate base on the diagonal.
  • then flip the matrix horizonally.
C++ Solution
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        if(matrix.empty()) return;
        if(matrix[0].size() != matrix.size()) return;

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


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

        return;
    }
};
Java Solution
public class Solution {
    public void rotate(int[][] matrix) {
         if(matrix.length == 0) return;
        if(matrix[0].length != matrix.length) return;

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


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

        return;
    }
}
Comment

Nothing interesting.

results matching ""

    No results matching ""