C++实现:
#include <iostream>
using namespace std;
int main()
{
int array[2][3] = {1, 2, 3, 4, 5, 6};
int transposeMat[3][2];
cout<<"array = "<<endl;
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++){
cout<<array[i][j]<<"\t";
}
cout<<endl;
}
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
transposeMat[j][i] = array[i][j];
}
}
cout<<"transposeMat = "<<endl;
for (int i=0; i<3; i++)
{
for (int j=0; j<2; j++)
{
cout<<transposeMat[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Java实现:
package com.datastructure;
public class MatrixTransposition {
public static void main(String[] args) {
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("array = ");
printMatrix(array);
reverse(array);
System.out.println("tsMat = ");
printMatrix(array);
System.out.println("----------------------");
int[][] mat = {{1, 2}, {3, 4}, {5, 6}};
System.out.println("mat = ");
printMatrix(mat);
System.out.println("tsMat = ");
printMatrix(transpose(mat, 3, 2));
}
public static void reverse(int matrix[][]) {
for (int i=0; i<matrix.length; i++) {
for (int j=i; j<matrix[i].length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
public static int[][] transpose(int[][] matrix, int row, int col) {
int[][] tsMat = new int[col][row];
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
tsMat[j][i] = matrix[i][j];
}
}
return tsMat;
}
public static void printMatrix(int matrix[][]) {
for (int i=0; i<matrix.length; i++) {
for (int j=0; j<matrix[i].length; j++) {
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
}