Skip to content

Latest commit

 

History

History
25 lines (21 loc) · 638 Bytes

566. Reshape the Matrix.md

File metadata and controls

25 lines (21 loc) · 638 Bytes

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==c*r:
            l=[]
            for i in range(m):
                for j in range(n):
                    l.append(mat[i][j])

            k=0
            x=[]
            for i in range(r):
                x.append(l[k:k+c])
                k=k+c

        else:
            x=mat

        return x

We must make sure to add the base condition of returning the original matrix if the given matrix's dimensions doesn't match the rehaped matrix's dimensions