title: Rotating a NxN matrix in Java
body: <p>This is a question from Cracking the Coding Interview. The solution says that the program rotates the exterior edges, then the interior edges. However, I'm having trouble following the logic of both the for loops. </p>
  
  <p>Could somebody explain the logic of the code (e.g. why they do "layer &lt; n/2" and the four steps of "left -> top" and "bottom -> left" etc)? On a side note, how would one's thought process be when coming up with this during a coding interview?</p>
  
  <blockquote>
    <p>Given an image represented by an NxN matrix, where each pixel in the
    image is 4 bytes, write a method to rotate the image by 90 degrees.
    Can you do this in place?</p>
  </blockquote>
  
  <pre><code>public static void rotate(int[][] matrix, int n) {
      for (int layer = 0; layer &lt; n / 2; ++layer) {
          int first = layer;
          int last = n - 1 - layer;
          for(int i = first; i &lt; last; ++i) {
              int offset = i - first;
              int top = matrix[first][i]; // save top
  
              // left -&gt; top
              matrix[first][i] = matrix[last-offset][first];          
  
              // bottom -&gt; left
              matrix[last-offset][first] = matrix[last][last - offset]; 
  
              // right -&gt; bottom
              matrix[last][last - offset] = matrix[i][last]; 
  
              // top -&gt; right
              matrix[i][last] = top; // right &lt;- saved top
          }
      }
  }
  </code></pre>