title: Rotate inner-square in 2D Array
body: <p>I want to rotate a inner square in a 2D Array like the 'Sample' image below:</p>
  
  <p><img src="https://i.stack.imgur.com/aJhgD.png" alt="Sample"></p>
  
  <p>Given top-left corner and bottom-right postion.</p>
  
  <p>I tried to split it to another 2d Array then rotate it. But it costs big O loop runtime and memory.</p>
  
  <pre><code>static int[][] rotateMatrix(int[][] subSquare) {
      int n = subSquare.length;
      int[][] temp = new int [n][n];
      for(int i = 0; i &lt; n; i++) {
          for(int j = 0; j &lt; n; j++) {
              temp[i][j] = subSquare[n - j - 1][i];
          }
      }
      return temp;
  }
  
  static int[][] getInnerSquare(int[][] square, int ai, int bi, int di){
      int g = 0, h = 0;
      int[][] innerSquare = new int[di+1][di+1];
      for(int k = ai - 1; k &lt; ai + di; k++) {
          for(int j = bi - 1; j &lt; bi + di; j++) {
              innerSquare[g][h] = square[k][j];
              h++;
          }
          g++;
          h=0;
      }
      return innerSquare;
  }
      static void replaceInnerSquare(int[][] square, int[][] innerSquare, int ai, int bi, int di) {
      int g = 0, h = 0;
      for(int i = ai - 1; i &lt; ai + di; i++) {
          for(int j = bi - 1; j &lt; bi + di; j++) {
              square[i][j] = innerSquare[g][h];
              h++;
          }
          g++;
          h=0;
      }
  }
  
  public static void main(String[] args){
      //follow the image: ai = 1, bi = 2, di = 3 
      // top-left corner (ai, bi), bottom-right corner(ai + di, bi + di)
      subSquare = getInnerSquare(square, ai, bi, di);         
      subSquare = rotateMatrix(subSquare);
      replaceInnerSquare(square, subSquare, ai, bi, di);
  }
  </code></pre>
  
  <p>Is there any better solution for this problem?
  Thanks!!!!</p>