[LeetCode] Transpose Matrix

867. Transpose Matrix

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s row and column indices.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
vector<vector<int>> res(m, vector<int>(n));
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
res[j][i] = matrix[i][j];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/transpose-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.