LeetCode – Rotate Image (Java)

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?

In-place Solution

By using the relation "matrix[i][j] = matrix[n-1-j][i]", we can loop through the matrix.

public void rotate(int[][] matrix) {
	int n = matrix.length;
	for (int i = 0; i < n / 2; i++) {
		for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
			int temp = matrix[i][j];
			matrix[i][j] = matrix[n-1-j][i];
			matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
			matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
			matrix[j][n-1-i] = temp;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. kinshuk chandra on 2014-4-28

    I liked the inplace solution. I have also done the same thing here – http://k2code.blogspot.in/2014/03/rotate-n-n-matrix-by-90-degrees.html

  2. A Programmer on 2014-6-29

    how would you do it counter clockwise?

  3. Guest on 2014-10-14

    If I is your matrix

    for i in range(n):

    print a

  4. my boo on 2015-2-22

    Your algorithm counter rotate the image instead of clock wise rotate.

  5. my boo on 2015-2-22

    my bad, I got the axis messed up.

  6. Chen Chen on 2015-9-9

    Great! Thanks for sharing.

  7. Ivy G on 2015-9-19

    You can replace “Math.ceil(((double) n) / 2.” with “(n+1)/2”

  8. svGuy on 2016-4-29

    its easier to transpose the matrix first and then swap columns for clockwise rotation.

  9. svGuy on 2016-5-3

    transpose the matrix and swap rows

  10. hina jain on 2016-5-3

    I think the j should be initialized to i instead of 0 in the second for loop.

  11. Guest on 2017-1-30

    why Math.ceil(((double) n) /2.) is used?

Leave a comment