```
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[][] res = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
res[i][j] = nums[(i * c + j) / n][(i * c + j) % n];
}
}
return res;
}
}
```