Leetcode 566. Reshape the Matrix
You are given a matrix represented as a 2D array of integers mat
and two integers r
and c
representing the row and column dimensions of the desired reshaped matrix.
Your task is to reshape the matrix mat
such that:
mat
are rearranged in row-major order into the new matrix with dimensions r x c
.If it is not possible to reshape the matrix to r x c
dimensions, the function should return the original matrix.
Answer: The number of elements in mat
will be between 1 and 100, inclusive. The matrix elements will be integers.
r
and c
:
r
and c
are always greater than zero?Answer: Yes, r
and c
will be positive integers.
r
and c
are such that reshaping the matrix is not possible?Answer: The function should return the original matrix if reshaping is not possible.
mat
equals r * c
. If not, return mat
unchanged.r x c
by filling it row by row using the elements from the flattened list.public class ReshapeMatrix {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int rows = mat.length;
int cols = mat[0].length;
// Check if reshaping is possible
if (rows * cols != r * c) {
return mat;
}
int[][] reshapedMatrix = new int[r][c];
int[] flatList = new int[rows * cols];
int index = 0;
// Flatten the original matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
flatList[index++] = mat[i][j];
}
}
// Fill the new reshaped matrix
index = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
reshapedMatrix[i][j] = flatList[index++];
}
}
return reshapedMatrix;
}
public static void main(String[] args) {
ReshapeMatrix solution = new ReshapeMatrix();
// Example test case
int[][] mat = // use example from above
int r = 1, c = 4;
int[][] result = solution.matrixReshape(mat, r, c);
// Print the result
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
flatList
array and the reshaped matrix structure.This approach ensures the task is completed efficiently and correctly, even for edge cases where reshaping might not be possible.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?