← Home

566. Reshape the Matrix

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
566

This is one of those problems where the clean idea matters more than the amount of code. For 566. Reshape the Matrix, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
03
04You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
05
06The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
07
08If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
09
10Example 1:
11Input: 
12nums = 
13[[1,2],
14 [3,4]]
15r = 1, c = 4
16Output: 
17[[1,2,3,4]]
18Explanation:
19The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
20Example 2:
21Input: 
22nums = 
23[[1,2],
24 [3,4]]
25r = 2, c = 4
26Output: 
27[[1,2],
28 [3,4]]
29Explanation:
30There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
31**/
32
33//Runtime: 36 ms, faster than 100.00% of C++ online submissions for Reshape the Matrix.
34//Memory Usage: 12.4 MB, less than 27.38% of C++ online submissions for Reshape the Matrix.
35
36class Solution {
37public:
38    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
39        if(r*c!=nums.size()*nums[0].size()){
40            return nums;
41        }
42        vector<vector<int>> ans(r, vector<int>(c));
43        int idx = 0;
44        
45        for(vector<int> v : nums){
46            for(int e : v){
47                ans[idx/c][idx%c] = e;
48                idx++;
49            }
50        }
51        return ans;
52    }
53};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.