给出一个矩阵,得到他的转置矩阵,输入以及要求输出如下:
e.g.0.1 示例1 3*3矩阵
Input
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7 e.g.0.2 示例2 4*4矩阵
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13Code.1.1 示例程序C++版
#include <iostream>
#define N 4
using namespace std;
void displayMatrix(int mat[N][N]);
void rotateMatrix(int mat[][N])
{
for (int x = 0; x < N / 2; x++)
{
for (int y = x; y < N-x-1; y++)
{
int temp = mat[x][y];
mat[x][y] = mat[y][N-1-x];
mat[y][N-1-x] = mat[N-1-x][N-1-y];
mat[N-1-x][N-1-y] = mat[N-1-y][x];
mat[N-1-y][x] = temp;
}
}
}
void displayMatrix(int mat[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout << mat[i][j]<< " ";
cout << endl;
}
cout << endl;
}
int main()
{
int mat[N][N] =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
rotateMatrix(mat);
displayMatrix(mat);
return 0;
} Code.1.1 示例程序Python版
N = 4
def rotateMatrix(mat):
for x in range(0, int(N/2)):
for y in range(x, N-x-1):
temp = mat[x][y]
mat[x][y] = mat[y][N-1-x]
mat[y][N-1-x] = mat[N-1-x][N-1-y]
mat[N-1-x][N-1-y] = mat[N-1-y][x]
mat[N-1-y][x] = temp
def displayMatrix( mat ):
for i in range(0, N):
for j in range(0, N):
print (mat[i][j], end = ' ')
print ("")
mat = [[0 for x in range(N)] for y in range(N)]
mat = [ [1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ] ]
rotateMatrix(mat)
displayMatrix(mat)