8-lines Java solution


  • 9
    S

    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;
                }
            }
        }
    }

  • 0
    O

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


  • 0
    S

    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.


  • 1
    D

    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.


  • 0

    Very easy to understand this one. :) Thanks.


Log in to reply
 

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