[LeetCode] Reshape the Matrix

아르당·2026년 1월 29일

LeetCode

목록 보기
120/134
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

MATLAB에는 원래 데이터를 유지하면서 m x n 행렬을 r x c 크기의 새로운 행렬로 변환할 수 있는 편리한 함수인 reshape가 있다.

m x n 행렬 mat와 원하는 재구성된 행렬의 행 수와 열 수를 나타내는 두 정수 r과 c가 주어진다.

재구성된 행렬은 원래 행렬의 모든 요소를 원래와 동일한 행 순회 순서로 채워야 한다.

주어진 매개변수를 사용한 재구성 작업이 가능하고 유효한 경우, 재구성된 새로운 행렬을 출력하고, 그렇지 않으면 원래 행렬을 출력해라.

Example

#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]]

Constraints

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

Solved

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;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글