[Python] One pass solution, explained
First approach is to reshape to line and then reshape it to new shape. However we can do smarter: just iterate over all elements line by line and use res[count/
First approach is to reshape to line and then reshape it to new shape. However we can do smarter: just iterate over all elements line by line and use `res[count//c][count\\%c] = nums[i][j]` to fill element by element. \n\n#### Complexity\nTime complexity is `O(mn)`, space complexity is `O(mn)`, but in fact it is `O(1)` if we do not count output array.\n\n#### Code\n```python\nclass Solution:\n    def matrixReshape(self, nums, r, c):\n        m, n, count = len(nums), len(nums[0]), 0\n        if m*n != r*c: return nums\n        res = [[0] * c for _ in range(r)]\n        for i, j in product(range(m), range(n)):\n            res[count//c][count%c] = nums[i][j]\n            count += 1      \n        return res\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
['Math', 'Matrix']