Reshape the Matrix

Problem Id: 566 Difficulty: Easy


Intuition

Solution


class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(nums), len(nums[0])
        if m * n != r * c:
            return nums
        ans = []
        i, j, x, y = 0, 0, 0, 0
        while True:
            if j == n:
                i += 1
                j = 0
            if y == c:
                x += 1
                y = 0
            if i == m:
                return ans
            if y == 0:
                ans.append([])
            ans[x].append(nums[i][j])
            j += 1
            y += 1