# [C++] [Java] Clean Code - 5 lines (2 Solution)

• Java

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

C++

``````class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size(), n = nums[0].size(), o = m * n;
if (r * c != o) return nums;
vector<vector<int>> res(r, vector<int>(c, 0));
for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n];
return res;
}
};
``````
``````class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size(), n = nums[0].size();
if (m * n != r * c) {
return nums;
}

vector<vector<int>> res(r, vector<int>(c, 0));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int k = i * n + j;
res[k / c][k % c] = nums[i][j];
}
}

return res;
}
};
``````

• This post is deleted!

• There is no need to re-calculate `k` every time, just do it like this:

``````for (int i = 0, k = 0; i < m; i++)
for (int j = 0; j < n; j++, k++)
res[k / c][k % c] = nums[i][j];
``````

• ``````public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums == null || nums.length == 0 || nums[0].length == 0) return nums;
if (nums.length * nums[0].length != r * c) return nums;

int reshapeCnt = 0;
int[][] reshapedNums = new int[r][c];
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length; col++) {
reshapedNums[reshapeCnt / c][reshapeCnt % c] = nums[row][col];
reshapeCnt++;
}
}

return reshapedNums;
}
}

``````

• @vicch7 Lucid solution, thanks. :)

• What if the input was :
[[1,2,3,4],[5,6]]
2
3

Wouldn't it return the original instead of breaking it into two even vectors?

• @KkevinLi I think the definition of matrix exclude that case.

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