Java Accepted solution - rotate one border at a time


  • 0
    D

    e.g. n = 5, first rotate 1111 to 2222, then 2222 to 3333, etc.

    11112

    4xxx2

    4xxx2

    4xxx2

    43333

    public class Solution {
        public void rotate(int[][] M) {
            int n = M.length;
            int j = 0;
            while (j + j + 1 < n) {
                int m = n - j - j;
                int[] temp = new int[m-1];  // save the current border
                for (int i = 0; i < m-1; i++)
                    temp[i] = M[n-1-j-i][j];
                for (int i = 0; i < m-1; i++) 
                    M[n-1-j-i][j] = M[n-1-j][n-1-j-i];
                for (int i = 0; i < m-1; i++)
                    M[n-1-j][n-1-j-i] = M[j+i][n-1-j];
                for (int i = 0; i < m-1; i++)
                    M[j+i][n-1-j] = M[j][j+i];
                for (int i = 0; i < m-1; i++)
                    M[j][j+i] = temp[i];
                j++;
            }
        }
    }

Log in to reply
 

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