rotate Matrix In Place - Java java.lang

Java examples for java.lang:Math Matrix

Description

rotate Matrix In Place

Demo Code


//package com.java2s;

public class Main {
    static int[][] rotateMatrixInPlace(int[][] arr) {
        int n = arr.length;
        for (int layer = 0; layer < n / 2; layer++) {
            int first = layer;
            int last = n - 1 - layer;
            for (int i = first; i < last; i++) {
                int offset = i - first;
                int top = arr[first][i]; // save top
                // left -> top
                arr[first][i] = arr[last - offset][first];
                // bottom -> left
                arr[last - offset][first] = arr[last][last - offset];
                // right -> bottom
                arr[last][last - offset] = arr[i][last];
                // top -> right
                arr[i][last] = top;/*  w w w  .  ja va2  s  .  c  o m*/
            }
        }
        return arr;
    }
}

Related Tutorials