Simple python solution with detailed explaination


  • 0
    Y

    The key point of this problem is to check whether the number of original matrix equals to the reshape target, that is n=r multiply c, n means the total number of the original matrix.
    Step1, check the 'n==r multiply c', if not, the original numbers could not fill in the new matrix, and then return the original one
    Step2, creat target reshape matrix by filling zeros, or other numbers you like :) , anyway, they'll finally be substituded by the numbers from nums
    Step3, store the traversal numbers from original list in a one dimension array
    Step4, fill in the reshape matrix with the traversal array.

        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            if nums==[]:return []
            if r*c!=len(nums)*len(nums[0]):return nums
            matrix=[[0 for col in range(c)] for row in range(r)]
            reversal=[]
            for i in range(len(nums)):
                for j in range(len(nums[0])):
                    traversal.append(nums[i][j])
            k=0
            for i in range(r):
                for j in range(c):
                    matrix[i][j]=traversal[k]
                    k+=1
            return matrix
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.