Problem Description
Given an m x n matrix and two integers r and c, reshape the matrix into a new matrix with dimensions r x c by taking elements in row-traversing order from the original matrix. If the total number of elements does not match (i.e., if m * n ≠ r * c), return the original matrix.
Key Insights
- Check if the reshape operation is possible by comparing the total elements (m * n with r * c).
- Flatten the original matrix while preserving the row-traversing order.
- Use the flattened list to build the new matrix row by row.
- If the total number of elements does not match, simply return the original matrix.
Space and Time Complexity
Time Complexity: O(mn) as we iterate through all elements of the matrix once. Space Complexity: O(mn) for the additional list used to store flattened elements (or the new matrix).
Solution
The solution involves first checking whether the reshape is possible by ensuring that the product of the rows and columns of the original matrix equals that of the desired matrix (r * c). If not, the original matrix is returned. Otherwise, the matrix is flattened into a one-dimensional list, preserving the row-order traversal. Finally, the flattened list is segmented by the new column size c to form the reshaped matrix. The primary data structures used include a list (or array) for flattening the matrix and then another list (or vector/array) to hold the final reshaped matrix.