First, the array matrix remodeling ※ ---

In MATLAB, there is a very useful function of the RESHAPE, it may be a matrix remodeling a different size of the new matrix but retain their original data.

A matrix representation is given by two-dimensional array, and the number of rows and columns of the two positive integers r and C, respectively, represent the desired reconstructed matrix.

The reconstructed matrix requires all elements of the original matrix filled in the same row traversal order.

If the operation has reshape the given parameters are feasible and reasonable, new output matrix remodeling; otherwise, the output of the original matrix.

Example 1:

Input:
nums =
[[1,2],
[3,4-]]
R & lt =. 1,. 4 C =
Output:
[[1,2,3,4]]
Explanation:
the rows in the result of nums [1,2, 3,4]. The new matrix is a 4 * 1 matrix, with the element values before filling a new matrix row by row.
Example 2:

Input:
the nums =
[[1,2],
[3,4]]
R & lt = 2, C =. 4
Output:
[[1,2],
[3,4]]
Explanation:
no way be converted to the 2 * 2 matrix 2 * 4 matrix. Therefore, the output of the original matrix.
note:

To the width and height of the matrix in a given range [1, 100].
Given r and c are positive.

 1 class Solution {
 2 public:
 3     vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
 4         int old_r = nums.size();
 5         int old_c = nums[0].size();
 6         int new_r = 0;
 7         int new_c = 0;
 8         vector<vector<int> > res(r,vector<int>(c));
 9         if((old_r*old_c) != (r*c)) return nums;
10         for(int i=0;i<old_r;i++){
11             if(new_r == r) break;
12             for(int j=0;j<old_c;j++){
13                 res[new_r][new_c] = nums[i][j];
14                 new_c+=1;
15                 if(new_c == c){
16                     new_c = 0;
17                     new_r += 1;
18                 }
19                  
20             }
21         }
22         return res;
23     }
24 };

 

Guess you like

Origin www.cnblogs.com/pacino12134/p/11010089.html