Leetcode No.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?

First Answer With Recursion

One simple method is rotate the array layer by layer like following.

So the most simple answer with recursion is following.

Second Answer Without Recursion

With the same method, recursion itself contributes to wasting time. As a result, we can optimize it by realizing the algorithm straightly.

Third Answer With easier method

refer:AC Java in place solution with explanation Easy to understand.

If we want to rotate the matrix clockwise, we can flip it symmetrically at first, and secondly flip the matrix horizontally. Like following.

And code is following.

Leave a Reply

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