1. Description
In MATLAB, there is a handy function called reshape which can reshape an $m \times n$ matrix into a new one with a different size $r \times c$ keeping its original data.
You are given an $m \times n$ 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 elements 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.
constraints :
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 100
- -1000 <= mat[i][j] <= 1000
- 1 <= r, c <= 300
2. Algorithms
First of all, we have to check if the reshape operation with given parameter is possible and legal. The conditions to checking legal is row times col of mat == r times c.
We will change mat into \(1 \times (n \times p)\) matrix first, and then pop every c elements from previous matrix and update to result matrix.
- Start
- Calculate the number of rows and cols of input matrix. Store result into variable named n and p.
- If n * p != r * c, return mat.
- Declare variable named J initialized with empty list.
- For integer i through 0 to n-1,
- For integer j through 0 to p-1,
- Store mat[i][j] into J
- For integer j through 0 to p-1,
- Declare three variables named rcount, coef, res.
- Initialize them to 0, 0, [].
- Repeat the steps until rcount == r.
- Calculate left index with c * coef. (0, c, 2c, ...)
- Calculate right index with c * (coef + 1). (c, 2c, ...)
- Append J[left : right] into res.
- Increment coef and rcount by 1.
- Return res matrix.
- End
3. Codes
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
# Check if the reshape operation is illegal
# n : the number of row of input matrix
# p : the number of col of input matrix
n, p = len(mat), len(mat[0])
# Return original matrix if the reshape operation is illegal
if n * p != r * c :
return mat
J = []
for i in range(n) :
for j in range(p) :
J.append(mat[i][j])
rcount, coef, res = 0, 0, []
while rcount < r :
left = c * coef
right = c * (coef + 1)
res.append(J[left:right])
coef += 1
rcount += 1
return res
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
575 Distribute Candies (0) | 2022.09.07 |
---|---|
572 Subtree of Another Tree (0) | 2022.09.06 |
563 Binary Tree Tilt (0) | 2022.09.06 |
561 Array Partition (0) | 2022.09.06 |
559 Maximum Depth of N-ary Tree (0) | 2022.09.06 |