题解 | #矩阵交换#
矩阵交换
http://www.nowcoder.com/practice/ec44d4ff8c794b2f9205bdddbde96817
#include <stdlib.h>
#include <assert.h>
void C_Transposition(int *p, int n, int m, int x, int y) //列变换
{
int i;
for(i = 0; i < n; i++)
{
int tmp;
tmp = p[(x - 1) + m * i]; //x列的位置
p[(x - 1) + m * i] = p[(y - 1) + m * i];
p[(y - 1) + m * i] = tmp;
}
}
void R_Transposition(int *p, int n, int m, int x, int y) //行变换
{
int i;
for(i = 0; i < m; i++)
{
int tmp;
tmp = p[(x - 1) * m + i];
p[(x - 1) * m + i] = p[(y - 1) * m + i];
p[(y - 1) * m + i] = tmp;
}
}
int main()
{
int n,m,i,j,x,y,k;
char t;
int *p;
scanf("%d %d", &n, &m);
p = (int*)malloc((n * m) * sizeof(int));
assert(p);
for(i = 0; i < m * n; i++)
{
scanf("%d ", &p[i]);
}
scanf("%d ", &k);
while(~scanf("%c %d %d", &t, &x, &y))
{
if(t == 'c')
{
C_Transposition(p, n, m, x, y);
}
else if(t == 'r')
{
R_Transposition(p, n, m, x, y);
}
}
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
printf("%d ", p[i * m + j]);
}
printf("\n");
}
return 0;
}