2차원 배열의 크기를 정사각형으로 만드는게 관건)
int[][] arr = {
{1, 2, 3},
{4, 5, 6}
};
if (col > row) {
int[][] temp = new int[col][col]; // 새로운 3x3 배열을 만듭니다.
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
temp[j][i] = arr[j][i]; // 원래 배열의 값을 새로운 배열에 복사합니다.
}
// temp[row][i] = 0; // 주석 처리된 부분: 각 열의 마지막 행에 0을 추가하려는 시도
}
return temp; // 새로운 배열을 반환합니다.
}
int[][] arr = {
{1, 2},
{3, 4},
{5, 6}
};
if (row > col) {
int[][] temp = new int[row][row]; // 새로운 3x3 배열을 만듭니다.
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
temp[i][j] = arr[i][j]; // 원래 배열의 값을 새로운 배열에 복사합니다.
}
temp[i][col] = 0; // 각 행의 마지막 열에 0을 추가합니다.
}
return temp; // 새로운 배열을 반환합니다.
}
쉽게 생각하면 답 나옴. 정사각형이니 길이가 긴 쪽으로 배열 만들어 주고, 배열 생성시 빈 값은 0으로 채워진다는 점 고려하면 됨
class Solution {
public int[][] solution(int[][] arr) {
//2024 07 27 3차 수정
int row = arr.length;
int col = arr[0].length;
if(row > col){
int[][] rectangle = new int[row][row];
for(int i=0 ; i < row ; i++){
for(int j=0 ; j < col ; j++){
rectangle[i][j] = arr[i][j];
}
}
return rectangle;
}else if(col > row){
int[][] rectangle = new int[col][col];
for(int i=0 ; i < row ; i++){
for(int j=0 ; j <col ; j++){
rectangle[i][j] = arr[i][j];
}
}
return rectangle;
}else {
return arr;
}
}
}