Leetcode: Rotate Image

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?

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        if (n <= 1 || matrix.length <= 1 || n != matrix.length) {
            return;
        }
        int mid = (n - 1) / 2;
        int offset = 0;
        while (offset <= mid) {
            for (int i = offset; i < n - 1 - offset; i++) {
                int tmp = matrix[offset][i];
                matrix[offset][i] = matrix[n - 1 - i][offset];
                matrix[n - 1 - i][offset] = matrix[n - 1 - offset][n - 1 - i];
                matrix[n - 1 - offset][n - 1 - i] = matrix[i][n - 1 - offset];
                matrix[i][n - 1 - offset] = tmp;
            }
            offset++;
        }

    }
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *