分别用c++,python,java写一个行列转换的算法

分别用c++,python,java写一个行列转换的算法,将这个矩阵转换一下:[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

以下是使用C++、Python 和 Java 编写的矩阵行列转换算法,并将给定矩阵转置的示例:

C++ 示例:
#include 
#include 

int main() {
    std::vector<std::vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
        {10, 11, 12}
    };

    int rows = matrix.size();
    int cols = matrix[0].size();

    // 创建一个新的矩阵来存储转置结果
    std::vector<std::vector<int>> transpose(cols, std::vector<int>(rows));

    // 转置矩阵
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }

    // 打印转置矩阵
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << transpose[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
Python 示例:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [10, 11, 12]
]

# 获取原矩阵的行数和列数
rows = len(matrix)
cols = len(matrix[0])

# 创建一个新矩阵来存储转置结果
transpose = [[0] * rows for _ in range(cols)]

# 转置矩阵
for i in range(rows):
    for j in range(cols):
        transpose[j][i] = matrix[i][j]

# 打印转置矩阵
for i in range(cols):
    for j in range(rows):
        print(transpose[i][j], end=" ")
    print()
Java 示例:
public class MatrixTranspose {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9},
            {10, 11, 12}
        };

        int rows = matrix.length;
        int cols = matrix[0].length;

        // 创建一个新的矩阵来存储转置结果
        int[][] transpose = new int[cols][rows];

        // 转置矩阵
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                transpose[j][i] = matrix[i][j];
            }
        }

        // 打印转置矩阵
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(transpose[i][j] + " ");
            }
            System.out.println();
        }
    }
}

这些示例会将给定的矩阵转置,并打印出转置后的结果。

你可能感兴趣的:(#,算法面试题,#,信息学奥赛,c++,python,java)