原問題網址:867. Transpose Matrix
問題描述
給定 2D 整數陣列 matrix
,return 它的轉置矩陣。
解題思路
這一題本身沒什麼難度,算是滿經典的題目。唯一要注意的是參數中的 int** returnColumnSizes
是「pointer to a pointer to an integer」。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** transpose(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes){
int row = matrixSize;
int col = *matrixColSize;
*returnSize = col;
*returnColumnSizes = malloc(sizeof(int) * col);
for (int i = 0; i < col; i++) {
(*returnColumnSizes)[i] = row;
}
int **transposedMatrix = malloc(sizeof(int*) * col);
for (int i = 0; i < col; i++) {
transposedMatrix[i] = malloc(sizeof(int) * row);
}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
transposedMatrix[i][j] = matrix[j][i];
}
}
return transposedMatrix;
}