[leetcode] 566. Reshape the Matrix

섬섬's 개발일지·2022년 1월 29일
0

leetcode

목록 보기
20/23

566. Reshape the Matrix

Problem

In MATLAB, there is a handy function called reshape which can reshape an mxn matrix into a new one with a different size rxc keeping its original data.

You are given an mxn matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elemetns of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input : mat = [[1,2],[3,4]], r = 1, c = 4
Output : [[1,2,3,4]]

Example 2:

input = [[1,2],[3,4]], r = 2, c = 4
Output : [[1,2],[3,4]]

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

코드

class Solution(object):
    def matrixReshape(self, mat, r, c):
        """
        :type mat: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        m = len(mat)
        n = len(mat[0])
        
        if m*n != r*c :
            return mat
        elif m == r and n == c :
            return mat
        
        row = 0
        column = 0
        
        result = [[0]*c for _ in range(r)]
        for i in range(m) :
            for j in range(n) :
                result[row][column] = mat[i][j]
                column += 1
                if column == c :
                    row += 1
                    column = 0
        
        return result
profile
섬나라 개발자

0개의 댓글