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?

Analysis

  • 一层一层的copy,就可以in-place rotate
  • 注意小心index,比如left的x index是last-i+first。因为i是从first开始的,代表这个index是last, last-1, last-2, etc.

Code

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int layer =0; layer<n/2; layer++){
            int first = layer;
            int last = n - 1 - layer;
            for (int i=first; i<last; ++i){
                int top = matrix[first][i];
                //top = left
                matrix[first][i]=matrix[last-i+first][first];
                //left = bottom
                matrix[last-i+first][first]=matrix[last][last-i+first];
                //bottom = right
                matrix[last][last-i+first]=matrix[i][last];
                //right = top
                matrix[i][last]=top;
            }
        }
    }

    //rotate counter-clockwise
    public void rotateCounter(int[][] matrix){
        int n = matrix.length;
        for (int layer =0; layer<n/2; layer++){
            int first = layer;
            int last = n - 1 - layer;
            for (int i=first; i<last; ++i){
                int top = matrix[first][i];
                matrix[first][i]=matrix[i][last];
                matrix[i][last]=matrix[last][last-i+first];
                matrix[last][last-i+first]=matrix[last-i+first][first];
                matrix[last-i+first][first]=top;
            }
        }
    }
}