# Reshape the Matrix

• Click here to see the full blog post

• /**

• Return an array of arrays of size *returnSize.
• The sizes of the arrays are returned as *columnSizes array.
• Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/

int** matrixReshape(int** nums, int numsRowSize, int numsColSize, int r, int c, int** columnSizes, int* returnSize) {
if(numsRowSize * numsColSize!=r * c)
{
return nums;
}
int** result=(int**)malloc(r * sizeof(int * ));
int k=0;
for(int i=0;i<r;i++)
{
result[i]=(int* )malloc (c * sizeof(int ));
for(int j=0;j<c;j++,k++)
{
result[i][j]=nums[k/numsColSize][k%numsColSize];
}
}
return result;
}
why is this solution wrong?

• This post is deleted!

• I don't know bro. This sorta worked for me (solution in C++):

class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int size = nums.size();
int size2 = nums[0].size();

``````    if ((size * size2) != r * c) return nums;

int d = 0;

vector<int>::iterator v2 = nums[0].begin();
vector<vector<int>> b;
vector<int> *degrees = new vector<int>;
for (int i=0; i < r; i++)
{

for (int j=0; j<c; j++)
{
if (v2 == nums[d].end())
{
d++;
v2 = nums[d].begin();
}
degrees->push_back(*v2);
v2++;
}
b.push_back(*degrees);
degrees = new vector<int>;
}
return b;
}
``````

};

• @michael_wolodkowicz
Thanks for your reply!
I know how to solve this problem in C++ or JAVA
I just want to know how to sovle it in C,and find errors in my code.

• O(m*n) easy code of C++

class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
//no matrix
if (r*c>nums.size()*nums[0].size())return nums;

``````    vector<vector<int>> arr;
arr.resize(r);//r rows
for (int k = 0; k < r; ++k){
arr[k].resize(c);//c colums
}

int r_num = nums.size(),c_num = nums[0].size();

int i=0,j=0,k=0,m=0;
while(i<r){
arr[i][j] = nums[k][m];
j++;m++;
if(j==c){
i++;
j=0;
}
if(m==c_num)
{
k++;
m=0;
}
}

return arr;
}
``````

};

• One for loop would do. I am still not sure how did people get 6ms AC though:

``````    public int[][] matrixReshape(int[][] nums, int r, int c) {
if(nums.length == 0 || nums[0].length == 0 || r == 0 || c == 0 || r*c != nums.length * nums[0].length) {
return nums;
}
int pre_r = nums.length, pre_c = nums[0].length, n = pre_r * pre_c;
int[][] res = new int[r][c];
for(int i = 0; i < n; i++){
res[i/c][i%c] = nums[i/pre_c][i%pre_c];
}
return res;
}
``````

• @alpenliebe said in Reshape the Matrix:

how did people get 6ms AC

Click on the 6ms bar and you'll see.

• Well, maybe the check is overcomplicated...
But overall a concept of "generator" looks nice, IMO :D

``````    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
const int m = nums.size();
const int n = nums[0].size();
const bool cond = (m  * n) / r == c && (m * n) % r == 0;

if (! cond)
return nums;

auto m1_printer = [&, i = 0, j = 0] () mutable
{
while (i < m && j < n)
{
const int out = nums[i][j];
if (++j == n)
{
i++;
j = 0;
}
return out;
}
throw std::length_error("l1");
};

vector<vector<int>> result(r, vector<int>(c));

auto m2_filler = [&, i = 0, j = 0] (int x) mutable
{
result[i][j] = x;
if (++j == c)
{
i++;
j = 0;
}
if (i > r) throw std::length_error("l2");
};

for (int i = 0; i < n * m; i++)
{
m2_filler(m1_printer());
}

return result;

}
``````

• my C++ solution

``````class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<vector<int>> newMatrix(r, vector<int>(c, 0));
int originalRaw = nums.size();
int originalColumn = nums[0].size();
if(originalRaw * originalColumn != r * c)
return nums;

int newRaw = 0, newColumn = 0;
for(int i = 0; i < originalRaw; i++)
{
for(int j = 0; j < originalColumn; j++)
{
newMatrix[newRaw][newColumn] = nums[i][j];
newColumn++;
if(newColumn == c)
{
newColumn = 0;
newRaw++;
}
}
}
return newMatrix;
}
};
``````

• Am I cheating?
import numpy as np
class Solution(object):
def matrixReshape(self,nums,r,c):
arr=np.array(nums)
if np.shape(arr)[0]np.shape(arr)[1]<rc:
return nums
else:
result=np.reshape(arr,(r,c))
return result.tolist()

• This post is deleted!

• Python solution:

class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
original_size = len(nums) * len(nums[0])

``````    if r * c > original_size:
return nums
else:
temp = [[0 for i in xrange(c)] for j in xrange(r)]
#Flatten the original num
nums_flattened = [i for row in nums for i in row]
for i in xrange(r):
for j in xrange(c):
temp[i][j] = nums_flattened[i * c + j]

nums = temp
return nums``````

• Simple Java Solution :

public int[][] matrixReshape(int[][] nums, int r, int c) {
int rowOld = nums.length;
int colOld = nums[0].length;
if((rowOld/r ) != (c/colOld)) {
return nums;
}
int rCount = 0;
int cCount = 0;
int[][] arr = new int[r][c];

``````    for(int i = 0; i < rowOld;i++) {
for(int j = 0; j < colOld; j++) {
if(cCount == c) {
cCount = 0;
rCount = rCount + 1;
}
arr[rCount][cCount] = nums[i][j];
cCount++;
}
}
return arr;
}``````

• class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if(nums.lengthnums[0].length != rc){
return nums;
}

``````    int reverse[][] = new int[r][c];
int k=0,m=0;
int i=0,j=0;
for(k = 0; k<r;k++){
for( m=0;m<c;m++){
if(j == nums[0].length){
j = 0;
i++;
}

int num = nums[i][j++];
reverse[k][m]= num;
}
}

return reverse;
}
``````

}

• Python Code:

``````A = [x for row in nums for x in row ]
if r * c == len(A):
return [A[i*c : (i + 1)*c] for i in range(r) ]
else:
return nums
``````

• Python solution:

``````class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
matrix=[]
one_row=[]
for i in nums:
for j in i:
one_row.append(j)
if r*c == len(one_row):
for i in range(0,len(one_row),c):
matrix.append(one_row[i:i+c])
return matrix
else:
return nums
``````

• What's the purpose of `int count = 0;` in the first approach?
It never been used.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.