> File Name: matrix_transpose.cpp
> Author: SongLee
> Modified: JCChan
************************************************************************/
#include<iostream>
using namespace std;
int getNext(int i, int m, int n)
{
return (i%n)*m + i / n;
}
int getPre(int i, int m, int n)
{
return (i%m)*n + i / m;
}
void movedata(int *mtx, int i, int m, int n)
{
int temp = mtx[i];
int cur = i;
int pre = getPre(cur, m, n);
while (pre != i)
{
mtx[cur] = mtx[pre];
cur = pre;
pre = getPre(cur, m, n);
}
mtx[cur] = temp;
}
void transpose(int *mtx, int m, int n)
{
for (int i = 0; i<m*n; ++i)
{
int next = getNext(i, m, n);
while (next > i)
next = getNext(next, m, n);
if (next == i)
movedata(mtx, i, m, n);
}
}
void input(int *mtx, int row, int column) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
cout << "请输入矩阵的第" << i + 1 << "行第" << j + 1 << "个元素:";
cin >> *(mtx + column*i + j);
}
}
}
void print(int *mtx, int m, int n)
{
for (int i = 0; i<m*n; ++i)
{
if ((i + 1) % n == 0)
cout << mtx[i] << "\n";
else
cout << mtx[i] << " ";
}
}
int main()
{
int row, column;
cout << "请输入矩阵的行数:";
cin >> row;
cout << "请输入矩阵的列数:";
cin >> column;
int *matrix = new int[row*column];
input(matrix, row, column);
cout << "Before matrix transposition:" << endl;
print(matrix, row, column);
transpose(matrix, row, column);
cout << "After matrix transposition:" << endl;
print(matrix, column, row);
delete[] matrix;
system("pause");
return 0;
}