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.
1def matrixReshape(mat, r, c):
2 m, n = len(mat), len(mat[0])
3 if m * n != r * c:
4 return mat
5
6 flat = [num for row in mat for num in row]
7 return [flat[i * c:(i + 1) * c] for i in range(r)]
8
This Python code flattens the 2D matrix into a 1D list and then reconstructs the list into a reshaped 2D list if dimensional constraints allow. Otherwise, it returns the original matrix.
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 <vector>
using namespace std;
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size(), n = mat[0].size();
if (m * n != r * c) return mat;
vector<vector<int>> newMat(r, vector<int>(c));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int index = i * n + j;
newMat[index / c][index % c] = mat[i][j];
}
}
return newMat;
}
This C++ code maintains element continuity via index coordination. Element addresses transition between matrices of differing dimensions by recalculating new indices without pre-flattening.