public class Transpose {
  
  /**
   * Given:
   * 1 2 3
   * 4 5 6
   * 7 8 9
   * 
   * Create a new array:
   * 1 4 7
   * 2 5 8
   * 3 6 9
   */   
  public static void transpose(int[][] matrix) {
    
    /** For each element (r,c) on the right-hand side
     * of the diagonal, swap it with element (c,r). */
    for(int r = 0; r < matrix.length; r++) {
      for(int c = r+1; c < matrix[r].length; c++) {
        int temp = matrix[r][c];
        matrix[r][c] = matrix[c][r];
        matrix[c][r] = temp;
      }
    }
    print(matrix);
  }
 
  public static void transpose2(int[][] matrix) {
    
    /** For each element (r,c) on the left-hand side
     * of the diagonal, swap it with element (c,r). */
    for(int r = 0; r < matrix.length; r++) {
      for(int c = 0; c < r; c++) {
        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[r].length; c++) {
        System.out.print(matrix[r][c] + " ");
      }
      System.out.println();
    }
  }
  
}
