# 566

# time: O(N * M)
# space: O(N * M)
class Solution:
    def reshape(self, nums, r, c):
        if not nums or len(nums) * len(nums[0]) != r * c:
            return nums

        rows, cols = len(nums), len(nums[0])
        
        queue = []
        for row in range(rows):
            for col in range(cols):
                queue.append(nums[row][col])
        
        res, count =[], 0

        for row in range(r):
            res.append([])
            for col in range(c):
                res[-1].append(queue[count])
                count += 1
        
        return res

# time: O(N * M)
# space: O(N * M)
class Solution2:
    def reshape(self, nums, r, c):
        if not nums or len(nums) * len(nums[0]) != r * c:
            return nums
        
        res = [[] * r]

        rows = cols = 0

        for i in range(len(nums)):
            for j in range(len(nums[0])):
                res[rows].append(nums[i][j])

                cols += 1
                if cols == c:
                    rows += 1
                    cols = 0
        
        return res


nums = [[1,2], [3,4]]
solution = Solution2()
print(solution.reshape(nums, 1, 4))