Monday, May 1, 2017

48. 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?



Solution:

Two steps to rotate the image:

1. Transpose the matrix. (swap [i][j] with [j][i])

1 2 3              1 4 7
4 5 6    ==>   2 5 8
7 8 9              3 6 9

2. Reverse the columns. (swap [i][j] with [i][n - j - 1])

1 4 7              7 4 1
2 5 8    ==>   8 5 2
3 6 9              9 6 3



Code:


public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                swap(matrix, i, j, j, i);
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n / 2; j++) {
                swap(matrix, i, j, i, n - j - 1);
            }
        }
    }
    
    public void swap(int[][] matrix, int x1, int y1, int x2, int y2) {
        int tmp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = tmp;
    }
}