566. Reshape the Matrix Flashcards
Can you set up variables for mat.length and mat[0].length?
let m = mat.length, n = mat[0].length;
Can you set up the restrict condition for return the original mat?
let m = mat.length, n = mat[0].length;
if (m * n !== r * c) return mat;
Can you set up variable res for empty two dimensional arrays and stack for empty array?
let m = mat.length, n = mat[0].length;
if (m * n !== r * c) return mat;
let res = new Array(r).fill(0).map(() => new Array(c).fill(0)), stack = [];
Can you loop through mat and push each element to the empty stack?
let m = mat.length, n = mat[0].length;
if (m * n !== r * c) return mat;
let res = new Array(r).fill(0).map(() => new Array(c).fill(0)), stack = [];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
stack.push(mat[i][j]);
}
}
Can you loop through from 0 to kth elements in stack and assign it to the empty two dimensional array res?
let m = mat.length, n = mat[0].length;
if (m * n !== r * c) return mat;
let res = new Array(r).fill(0).map(() => new Array(c).fill(0)), stack = [];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
stack.push(mat[i][j]);
}
}
let k = 0;
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
res[i][j] = stack[k];
k++;
}
}
Can you return the two dimensional array?
return res;