public class Matrix {
  
  /**
   * Take the transpose of the square matrix.
   * 
   * Do this "in place" (without an extra array).
   * 
   * For example,
   * 
   * 1 2 3         1 4 7
   * 4 5 6   -->   2 5 8
   * 7 8 9         3 6 9
   * 
   */ 
  public static void transpose(int[][] matrix) {
    
    for (int r = 0; r < matrix.length; r++) {
      for (int c = r; c <matrix[r].length; c++) {
        
        // swap element at r, c with element at c, r
        int temp = matrix[r][c];
        matrix[r][c] = matrix[c][r];
        matrix[c][r] = temp;
        
      }
    }
    
    print(matrix);
    
  }
  
  public static void print(int[][] matrix) {
    for (int r = 0; r < matrix.length; r++) {
      for (int c = 0; c < matrix.length; c++) {
        System.out.print(matrix[r][c] + " ");
      }
      System.out.println();
    }
  }  
}