""" 0566.1 - Solution 1 - Flatten and Rebuild """
#####################################################################################
# Imports
#####################################################################################
from typing import List
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
"""Reshape the Matrix Function"""
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
flat = [mat[i][j] for i in range(m) for j in range(n)]
result = []
for i in range(r):
result.append(flat[i * c : (i + 1) * c])
return result
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().matrixReshape([[1, 2], [3, 4]], 1, 4)) # [[1, 2, 3, 4]]
print(Solution().matrixReshape([[1, 2], [3, 4]], 2, 4)) # [[1, 2], [3, 4]]
print(Solution().matrixReshape([[1, 2], [3, 4]], 4, 1)) # [[1], [2], [3], [4]]
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0566.2 - Solution 2 - Index Mapping """
#####################################################################################
# Imports
#####################################################################################
from typing import List
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
"""Reshape the Matrix Function"""
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
result = [[0] * c for _ in range(r)]
for i in range(m * n):
result[i // c][i % c] = mat[i // n][i % n]
return result
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().matrixReshape([[1, 2], [3, 4]], 1, 4)) # [[1, 2, 3, 4]]
print(Solution().matrixReshape([[1, 2], [3, 4]], 2, 4)) # [[1, 2], [3, 4]]
print(Solution().matrixReshape([[1, 2], [3, 4]], 4, 1)) # [[1], [2], [3], [4]]
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()