矩阵转置

一般的矩阵专职算法复杂富为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
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值