数据结构--矩阵转置(C++/Java)

C++实现:

#include <iostream>
using namespace std;

int main()
{
	int array[2][3] = {1, 2, 3, 4, 5, 6};
	int transposeMat[3][2];
	cout<<"array = "<<endl;
	for (int i=0; i<2; i++)
	{
		for (int j=0; j<3; j++){
			cout<<array[i][j]<<"\t";
		}
		cout<<endl;
	}
	
	for (int i=0; i<2; i++)
	{
		for (int j=0; j<3; j++)
		{
			transposeMat[j][i] = array[i][j];
		}
	}
	cout<<"transposeMat = "<<endl;
	for (int i=0; i<3; i++)
	{
		for (int j=0; j<2; j++)
		{
			cout<<transposeMat[i][j]<<"\t";
		}
		cout<<endl;
	}
	
	return 0;
}

Java实现:

package com.datastructure;

public class MatrixTransposition {
	public static void main(String[] args) {
		int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
		System.out.println("array = ");
		printMatrix(array);
		reverse(array);
		System.out.println("tsMat = ");
		printMatrix(array);
		System.out.println("----------------------");
		
		int[][] mat = {{1, 2}, {3, 4}, {5, 6}};
		System.out.println("mat = ");
		printMatrix(mat);
		System.out.println("tsMat = ");
		printMatrix(transpose(mat, 3, 2));	
	}
	
	
	public static void reverse(int matrix[][]) {
		for (int i=0; i<matrix.length; i++) {
			for (int j=i; j<matrix[i].length; j++) {
				int temp = matrix[i][j];
				matrix[i][j] = matrix[j][i];
				matrix[j][i] = temp;		
			}
		}
	}
	
	public static int[][] transpose(int[][] matrix, int row, int col) {
		int[][] tsMat = new int[col][row];
		for (int i=0; i<row; i++) {
			for (int j=0; j<col; j++) {
				tsMat[j][i] = matrix[i][j];
			}
		}
		return tsMat;
	}
	
	public static void printMatrix(int matrix[][]) {
		for (int i=0; i<matrix.length; i++) {
			for (int j=0; j<matrix[i].length; j++) {
				System.out.print(matrix[i][j]+"\t");
			}
			System.out.println();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值