# Easy Java Solution

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

int[][] result = new int[r][c];
int row = 0, col = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[row][col] = nums[i][j];
col++;
if (col == c) {
col = 0;
row++;
}
}
}

return result;
}
}
``````

• This is exactly what I had :p

• @shawngao i think we have the same thought,but i additionally new the nums1 to place my result:

public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int a=nums.length;
int b=nums[0].length;
if(rc!=ab) return nums;
int[][] newNums=new int[r][c];
int[] nums1=new int[ab];
for(int i=0;i<a;i++){
for(int j=0;j<b;j++){
nums1[j+i
b]=nums[i][j];
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
newNums[i][j]=nums1[j+i*c];
}
}
return newNums;
}
}

• @shawngao what if the n (i.e.column length) are different?

• @kinsh
n different with what ?
output array result[][] is a new array .

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