# Leetcode Reshape-The-Matrix

#### 2022-06-12

---

##### Data structures:

#DS #array #vector

##### Difficulty:

#leetcode #coding_problem #difficulty-easy

##### Related topics:

##### Links:

- [Link to problem](https://leetcode.com/problems/reshape-the-matrix/)

---

### Problem

In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data.

You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the `reshape` operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

#### Examples

```markdown
**Input:** mat = [[1,2],[3,4]], r = 1, c = 4
**Output:** [[1,2,3,4]]
```

#### Constraints

- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 100
- -1000 <= mat[i][j] <= 1000
- 1 <= r, c <= 300

### Thoughts

First is the O(mn) solution, I use nested for loop with two additional vars

Then, from the hint, I know we can transform any array to 1-D, then transform 1-D to any array, that is to said:

> [!summary]
> For arr[m][n] and ans[r][c] and iterator i, with temp 1-D array temp[i]:
> temp[i] = arr[i / n][i % n] = ans[i / c][i % c]

### Solution

O(nm) solution using two loops

```cpp
class Solution {
public:
  vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
    // Initialize the answer vector
    vector<vector<int>> ans(r);
    for (int i = 0; i < ans.size(); i++) {
      ans[i] = vector<int>(c);
    }

    // if the vector is not possible, return original.
    if (mat[0].size() * mat.size() != r * c) {
      return mat;
    }

    int rCounter = 0;
    int cCounter = 0;
    for (int i = 0; i < mat.size(); i++) {
      for (int j = 0; j < mat[i].size(); j++) {
        if (cCounter >= c) {
          rCounter++;
          cCounter = cCounter % c;
        }

        ans[rCounter][cCounter++] = mat[i][j];
      }
    }
    return ans;
  }
};
```

O(mn) Solution using one loop

> [!tip]
> use `vector<vector<int>> ans(r, vector<int>(c));`
> to initialize a 2-d vector

```cpp
class Solution {
public:
  vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
    // Initialize the answer vector
    vector<vector<int>> ans(r, vector<int>(c));

    int m = mat.size();
    int n = mat[0].size();
    int total = m * n;

    // if the vector is not possible, return original.
    if (total != r * c) {
      return mat;
    }

    for (int i = 0; i < total; i++) {
      ans[i / c][i % c] = mat[i / n][i % n];
    }
    return ans;
  }
};
```
