auto-generated entry for Reshape the Matrix. the solution files are available below.
solution files
- C++
reshape-the-matrix/synced-solution.cpp - Python
reshape-the-matrix/synced-solution.py - TypeScript
reshape-the-matrix/synced-solution.ts
Collected C++, Python, TypeScript solutions for reshape the matrix. Add a dedicated write-up later if you want deeper notes.
auto-generated entry for Reshape the Matrix. the solution files are available below.
reshape-the-matrix/synced-solution.cppreshape-the-matrix/synced-solution.pyreshape-the-matrix/synced-solution.tsclass Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
rows = len(mat)
cols = len(mat[class="syntax-number">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(class="syntax-number">0, len(flattened), c)]
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int rows = mat.size();
int cols = mat[class="syntax-number">0].size();
if (rows * cols != r * c) {
return mat;
}
vector<vector<int>> result(r, vector<int>(c));
for (int index = class="syntax-number">0; index < rows * cols; index++) {
result[index / c][index % c] = mat[index / cols][index % cols];
}
return result;
}
};
function matrixReshape(mat: number[][], r: number, c: number): number[][] {
const rows = mat.length;
const cols = mat[class="syntax-number">0].length;
if (rows * cols !== r * c) {
return mat;
}
const result = Array.from({ length: r }, () => new Array<number>(c));
for (let index = class="syntax-number">0; index < rows * cols; index++) {
result[Math.floor(index / c)][index % c] = mat[Math.floor(index / cols)][index % cols];
}
return result;
}