Swap the rows and columns of a matrix so element [i][j] moves to [j][i] (an m x n matrix becomes n x m).
Allocate a result of transposed dimensions and copy each element to its swapped position; for a square matrix you can swap in place across the diagonal. O(m * n) time.
public static int[][] transpose(int[][] m) {
int rows = m.length, cols = m[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
t[j][i] = m[i][j];
return t;
}function transpose(m) {
return m[0].map((_, j) => m.map(row => row[j]));
}def transpose(m):
return [list(row) for row in zip(*m)]Transposition is a staple of data reshaping (rows-to-columns pivots) and linear-algebra routines used in analytics and graphics.
A candidate swaps in place with two nested loops over the full range and the matrix ends up unchanged. Why?