The Reshape the Matrix solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Reshape the Matrix
C++, Python and TypeScript solutions for Reshape the Matrix.
Solution files
Python•reshape-the-matrix/synced-solution.py
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
if rows * cols != r * c:
return mat
flattened = [value for row in mat for value in row]
return [flattened[i:i + c] for i in range(0, len(flattened), c)]
C++•reshape-the-matrix/synced-solution.cpp
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int rows = mat.size();
int cols = mat[0].size();
if (rows * cols != r * c) {
return mat;
}
vector<vector<int>> result(r, vector<int>(c));
for (int index = 0; index < rows * cols; index++) {
result[index / c][index % c] = mat[index / cols][index % cols];
}
return result;
}
};
TypeScript•reshape-the-matrix/synced-solution.ts
function matrixReshape(mat: number[][], r: number, c: number): number[][] {
const rows = mat.length;
const cols = mat[0].length;
if (rows * cols !== r * c) {
return mat;
}
const result = Array.from({ length: r }, () => new Array<number>(c));
for (let index = 0; index < rows * cols; index++) {
result[Math.floor(index / c)][index % c] = mat[Math.floor(index / cols)][index % cols];
}
return result;
}