一般的矩阵专职算法复杂富为o(n*m)的算法,但是今天数据结构书上学到一种o(num)num代表非零元素的个数的算法,但是复杂度降低了很多。。。
代码如下:
#include<cstdio>
#include<cstring>
const int maxn=100+10;
int a[maxn][maxn];//存储n*m的矩阵
typedef struct
{
int xx,yy,val;
}non_zero;
typedef struct
{
non_zero data[maxn];
int Row,Col,num_zero;
}Matrix;
Matrix old,New;
int n,m;
int col[maxn],num[maxn];
void init()
{
int cnt=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]!=0)
{
old.data[++cnt].xx=i;
old.data[cnt].yy=j;
old.data[cnt].val=a[i][j];
}
}
old.num_zero=cnt;
}
void change()
{
New.num_zero=old.num_zero;
New.Row=m;
New.Col=n;
}
void zhuanzhi()
{
int p,q;
for(int i=1;i<=old.num_zero;i++) ++num[old.data[i].yy];
col[1]=1;
for(int i=2;i<=m;i++) col[i]=col[i-1]+num[i-1];
for(int i=1;i<=old.num_zero;i++)
{
//printf("%d %d %d\n",old.data[i].xx,old.data[i].yy,old.data[i].val);
p=old.data[i].yy;
q=col[p];
New.data[q].xx=old.data[i].yy;
New.data[q].yy=old.data[i].xx;
New.data[q].val=old.data[i].val;
++col[p];
// printf("%d %d %d %d\n",q,New.data[q].xx,New.data[q].yy,New.data[q].val);
}
}
void print()
{
printf("num_zero:%d\n",New.num_zero);
for(int i=1;i<=New.num_zero;i++)
printf("%d %d %d %d\n",i,New.data[i].xx,New.data[i].yy,New.data[i].val);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(col,0,sizeof(col));
memset(num,0,sizeof(num));
init();//输入矩阵
change();//完善新的矩阵的信息
zhuanzhi();//矩阵的转置
printf("----------------------------------------------------\n");
print();
}
return 0;
}
/*
6 7
0 12 9 0 0 0 0
0 0 0 0 0 0 0
-3 0 0 0 0 14 0
0 0 24 0 0 0 0
0 18 0 0 0 0 0
15 0 0 -7 0 0 0
2 3
1 2 0
3 0 4
*/