LeetCode 566. Reshape the Matrix

In 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.

You'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.

The reshaped matrix need to 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.

Example 1:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The 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.

Example 2:

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

Note:

    1. The height and width of the given matrix is in range [1, 100].
    2. The given r and c are all positive.

题目不难理解,实现MATLAB中reshape函数,也就是改变矩阵维度但是不改变矩阵元素数目,只需要寻找某个元素在新旧矩阵中行列的表示方法就行

注意:用二维vector时,若使用二维数组的方式访问时,一定要先初始化,否则会出现访问越界的情况,代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
 4         //元素总数确定,直接寻找新矩阵和旧矩阵元素行列之间的关系即可
 5         int row = nums.size(), col = nums[0].size();
 6         int all = row * col;
 7         vector<vector<int>> res(r, vector<int>(c, 0));
 8         if (r * c != col * row)
 9             return nums;
10         for (int i = 0; i < all; i++)
11             res[i/c][i%c] = nums[i/col][i%col];
12         return res;
13     }
14 };

 

posted @ 2017-11-23 23:17  皇家大鹏鹏  阅读(209)  评论(0编辑  收藏  举报