数据结构29——稀疏矩阵转置

Description

输出稀疏矩阵的转置矩阵。(行列均不大于20)

Input

第一行输入两个正整数n和m,分别表示矩阵的行数和列数,
然后输入矩阵三元组,
最后输入(0 0 0)表示结束输入。

Output

转置后的矩阵。

  • Sample Input 
    4 4
    1 1 1
    2 1 2
    3 2 3
    0 0 0
  • Sample Output
    1 1 1
    1 2 2
    

    2 3 3

  • #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct node{
        int row;
    	int col;
    	int num;
    }node;
    
    typedef struct{
    	int cnt;
    	node matrix[405];
    }juzhen;
    
    void init(juzhen *p){
        int i=1,n,m;
    	int x,y,z;
    	scanf("%d%d",&n,&m);
    	while(i){
    		scanf("%d%d%d",&x,&y,&z);
    		if(!(x==0&&y==0&&z==0)){
    		    p->matrix[i].col = x;
                p->matrix[i].row = y;
                p->matrix[i].num = z;
                i++;
    		}
    		else{
    		    break;
    		}   
    	}
    	p->cnt=i-1;
    }
    
    void transposition(juzhen *p){
        int i,j;
    	int tmp;
    	for(i=1;i < p->cnt;i++){
    		for(j=i;j < p->cnt +1;j++){
    			if(p->matrix[i].row > p->matrix[j].row){
    			    tmp = p->matrix[i].row;
    				p->matrix[i].row = p->matrix[j].row;
    				p->matrix[j].row = tmp;
    				tmp =p ->matrix[i].col;
    				p->matrix[i].col = p->matrix[j].col;
    				p->matrix[j].col = tmp;
    				tmp = p->matrix[i].num;
    				p->matrix[i].num = p->matrix[j].num;
    				p->matrix[j].num = tmp;
    			}
    		}
    	}
    	for(i=1;i< p->cnt;i++){
    		for(j=i;j< p->cnt+1;j++){
    			if(p->matrix[i].row == p->matrix[j].row && p->matrix[i].col > p->matrix[j].col){
    			    tmp = p->matrix[i].col;
    				p->matrix[i].col = p->matrix[j].col;
    				p->matrix[j].col = tmp;
    				tmp = p->matrix[i].num;
    				p->matrix[i].num = p->matrix[j].num;
    				p->matrix[j].num = tmp;
    			}
    		}
    	}
    }
    
    void output(juzhen *p){
    	int tmp=1;
    	while((p->cnt)--){
    		if(p->cnt >0){
    		    printf("%d %d %d\n",p->matrix[tmp].row,p->matrix[tmp].col,p->matrix[tmp].num);
    		}
    		else{
    		   printf("%d %d %d",p->matrix[tmp].row,p->matrix[tmp].col,p->matrix[tmp].num);
    		}
    		tmp++;
    	}
    }
    
    int main(){
         juzhen *p=(juzhen *)malloc(sizeof(juzhen));
    	 init(p);
    	 transposition(p);
    	 output(p);
    	 return 0;
    }


猜你喜欢

转载自blog.csdn.net/chengchencheng/article/details/79931427
今日推荐