矩阵转置

GitHub跳转原题关系图返回列表

题目描述

输入一个 nn 行 mm 列的整数矩阵 AA,输出它的转置 ATA^T:一个 mm 行 nn 列的矩阵,满足 AT[j][i]=A[i][j]A^T[j][i]=A[i][j],即输出的第 jj 行恰好是原矩阵的第 jj 列。第一行包含 n,mn,m(1≤n,m≤1001\le n,m\le 100),随后 nn 行每行 mm 个 1∼10001\sim 1000 的整数;输出 mm 行每行 nn 个整数,相邻数用一个空格隔开。样例:输入 3 3 / 1 2 3 / 4 5 6 / 7 8 9,输出 1 4 7 / 2 5 8 / 3 6 9。

思路

转置是纯下标重排,不含任何计算。外层枚举输出行 jj(共 mm 个)、内层枚举 ii(共 nn 个),按顺序输出 a[i][j]a[i][j] 即可,复杂度 O(nm)O(nm),与读入同阶。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com  github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 20:02
# update_at: 2026-09-29 20:02

import sys
from collections.abc import Iterable, Iterator


def transpose(rows: Iterable[Iterable[int]]) -> Iterator[tuple[int, ...]]:
    """转置矩阵:第 j 行输出原矩阵的第 j 列。"""
    return zip(*rows)


def solve() -> None:
    lines = iter(sys.stdin.read().split('\n'))
    n, m = map(int, next(lines).split())                  # 行数 n、列数 m

    a = [list(map(int, next(lines).split())) for _ in range(n)]

    at = transpose(a)                                     # AT 共 m 行、每行 n 个
    sys.stdout.write('\n'.join(' '.join(map(str, row)) for row in at) + '\n')


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-04 22:12
 * update_at: 2026-10-05 02:40
 */
#include <iostream>
using namespace std;

typedef long long ll;

const int MAXN = 105; // n,m ≤ 100,留 5 余量

ll n, m;                // 原矩阵行数 n、列数 m
ll a[MAXN][MAXN];       // a[i][j] = 原矩阵第 i 行第 j 列的元素

void solve() {
    // 外层枚举输出行 j(即原矩阵的第 j 列),共 m 行
    for (ll j = 1; j <= m; j++) {
        for (ll i = 1; i <= n; i++) {
            if (i > 1) cout << ' ';
            cout << a[i][j];
        }
        cout << '\n';
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;
    for (ll i = 1; i <= n; i++) {
        for (ll j = 1; j <= m; j++) {
            cin >> a[i][j];
        }
    }

    solve();

    return 0;
}