LeetCode 566 Reinventing the LeetCode road of matrix HERODING

In MATLAB, there is a very useful function reshape, which can reshape a matrix into another new matrix with a different size, but retain its original data.

Given a matrix represented by a two-dimensional array, and two positive integers r and c, which respectively represent the number of rows and columns of the desired reconstructed matrix.

The reconstructed matrix needs to fill all the elements of the original matrix in the same row traversal order.

If the reshape operation with the given parameters is feasible and reasonable, the new reshape matrix is ​​output; otherwise, the original matrix is ​​output.

Example 1:

Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The result of row traversal nums is [1,2, 3,4]. The new matrix is ​​a 1 * 4 matrix, fill the new matrix line by line with the previous element values.

Example 2:

Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to convert a 2 * 2 matrix into 2 * 4 matrix. So output the original matrix.

note:

给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。

Source: LeetCode
Link: https://leetcode-cn.com/problems/reshape-the-matrix The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving idea: The
first step is to determine whether reshape can be performed, then observe whether r * c is consistent with the capacity of the matrix. If it is inconsistent, just return to the original array. If it is consistent, perform reshape. The reshape process is very simple, in fact it is quite. To arrange all the elements in the original matrix into a row, traverse one by one, perform assignment, the assignment process also has tricks, you have to know which row (i / col) the current number is in, which column it is in (i% col), and where the value is assigned. The ranks are similar, the code is as follows:

class Solution {
    
    
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
    
    
        int row = nums.size();
        int col = nums[0].size();
        // 如果矩阵中数量不一致,则返回原数组
        if(row * col != r * c) {
    
    
            return nums;
        }
        // 定义矩阵大小
        vector<vector<int>> ans(r, vector<int>(c));
        // 遍历矩阵,从头到尾
        for(int i = 0 ; i < row * col; i ++) {
    
    
            ans[i / c][i % c] = nums[i / col][i % col];
        }
        return ans;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/reshape-the-matrix/solution/czui-xiang-xi-ti-jie-by-heroding-ikmw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

Guess you like

Origin blog.csdn.net/HERODING23/article/details/113830131