# 8-lines Java solution

• Hi guys!

The idea is to loop through the top-left quadrant of the matrix (including the middle column for odd N), and for each element make 4-element swap (rotation). Meaning that for example if we have 5x5 M, and the current element is M[1,2] then we memorize M[1,2] into tmp and make: M[1,2] = M[2,1]; M[2,1] = M[3,2]; M[3,2] = M[2,3]; M[2,3] = tmp.

Here's a pretty concise code below.

``````public class Solution {
public void rotate(int[][] M) {
for (int i = 0; i < (M.length+1)/2; i++) {
for (int j = 0; j < M.length/2; j++) {
int tmp = M[i][j];
M[i][j] = M[M.length-j-1][i];
M[M.length-j-1][i] = M[M.length-i-1][M.length-j-1];
M[M.length-i-1][M.length-j-1] = M[j][M.length-i-1];
M[j][M.length-i-1] = tmp;
}
}
}
}``````

• can you explain the reason that outer loop with (M.length+1)/2 steps while inner loop has M.length/2?

• It's done for the case when M.length is an odd number. In that case we need to include the middle row and col and if there was M.length/2 we would miss them.

• The range for j can be narrowed to [i,M.length-i-1), and i<M.length/2 is enough, because we do not need to rotate the central point.

• Very easy to understand this one. :) Thanks.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.