Sponsored
Sponsored
This approach involves two main steps: flattening the original matrix into a one-dimensional array and then reconstructing it into the desired dimensions. The flattening process collects all elements by iterating row-wise over the original matrix. Then, if the total number of elements matches the product of new dimensions r
and c
, the method distributes these elements row-wise into the new matrix. If the element count does not match, the original matrix is returned.
Time Complexity: O(m * n) where m and n are the dimensions of the original matrix.
Space Complexity: O(r * c) for the reshaped matrix.
1#include <stdio.h>
2#include <stdlib.h>
3
4int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* returnSize, int** returnColumnSizes) {
5 int m = matSize, n = *matColSize;
6 if (m * n != r * c) {
7 *returnSize = m;
8 *returnColumnSizes = matColSize;
9 return mat;
10 }
11
12 int** newMat = (int**)malloc(sizeof(int*) * r);
13 *returnColumnSizes = (int*)malloc(sizeof(int) * r);
14 for (int i = 0; i < r; i++) {
15 newMat[i] = (int*)malloc(sizeof(int) * c);
16 (*returnColumnSizes)[i] = c;
17 }
18 *returnSize = r;
19
20 for (int i = 0; i < m * n; i++) {
21 newMat[i / c][i % c] = mat[i / n][i % n];
22 }
23 return newMat;
24}
25
The C code first checks if the reshape can be performed by comparing the number of elements in the original and desired matrices. If possible, it allocates memory for the new matrix and reshapes by using modulus and division to determine the new indices based on flattened array index i
.
Index Mirroring leverages mathematical transformation to directly address elements from the original matrix into the new shape without explicitly flattening. It avoids extra space for a flat array and directly computes 2D indices in the new layout.
Time Complexity: O(m * n).
Space Complexity: O(r * c) for storing reshaped matrix.
1#include
In this solution, we directly calculate the new position (index / c, index % c)
for elements from the original position (i, j)
in mat
, avoiding the need for an intermediate one-dimensional array.