문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
MATLAB에는 원래 데이터를 유지하면서 m x n 행렬을 r x c 크기의 새로운 행렬로 변환할 수 있는 편리한 함수인 reshape가 있다.
m x n 행렬 mat와 원하는 재구성된 행렬의 행 수와 열 수를 나타내는 두 정수 r과 c가 주어진다.
재구성된 행렬은 원래 행렬의 모든 요소를 원래와 동일한 행 순회 순서로 채워야 한다.
주어진 매개변수를 사용한 재구성 작업이 가능하고 유효한 경우, 재구성된 새로운 행렬을 출력하고, 그렇지 않으면 원래 행렬을 출력해라.
#1
Input: mat = [[1, 2], [3, 4]], r = 1, c = 4
Output: [[1, 2, 3, 4]]
#2
Input: mat = [[1, 2], [3, 4]], r = 2, c = 4
Output: [[1, 2], [3, 4]]
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int rows = mat.length;
int cols = mat[0].length;
if(rows * cols != r * c) return mat;
int[][] output = new int[r][c];
int output_rows = 0;
int output_cols = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
output[output_rows][output_cols] = mat[i][j];
output_cols++;
if(output_cols == c){
output_cols = 0;
output_rows++;
}
}
}
return output;
}
}