Leetcode 566 Solution

This article provides solution to leetcode question 566 (reshape-the-matrix)

https://leetcode.com/problems/reshape-the-matrix

Solution

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m = len(mat)
        n = len(mat[0])

        if m * n != r * c:
            return mat

        ans = [[0 for _ in range(c)] for _ in range(r)]

        for i in range(r):
            for j in range(c):
                k = i * c + j
                ans[i][j] = mat[k // n][k % n]

        return ans