반응형
문제
2021 데브매칭 - 행렬 테두리 회전하기
https://school.programmers.co.kr/learn/courses/30/lessons/77485
풀이
설명
각 회전들을 배열에 적용한 뒤, 그 회전에 의해 위치가 바뀐 숫자들 중 가장 작은 숫자들을 순서대로 구하는 문제입니다.
회전마다 시작 인덱스의 원소 값을 따로 저장하고, 회전이 끝난 뒤 그 값을 다시 넣어주면 쉽게 회전을 처리할 수 있습니다.
예시 코드
function solution(rows, columns, queries) {
const matrix = Array.from({ length: rows }, (_, i) =>
Array.from({ length: columns }, (_, j) => i * columns + j + 1)
);
const answer = [];
for (const [x1, y1, x2, y2] of queries) {
const temp = matrix[x1 - 1][y1 - 1];
let minValue = temp;
// 왼쪽
for (let i = x1 - 1; i < x2 - 1; i++) {
matrix[i][y1 - 1] = matrix[i + 1][y1 - 1];
minValue = Math.min(minValue, matrix[i][y1 - 1]);
}
// 아래쪽
for (let i = y1 - 1; i < y2 - 1; i++) {
matrix[x2 - 1][i] = matrix[x2 - 1][i + 1];
minValue = Math.min(minValue, matrix[x2 - 1][i]);
}
// 오른쪽
for (let i = x2 - 1; i > x1 - 1; i--) {
matrix[i][y2 - 1] = matrix[i - 1][y2 - 1];
minValue = Math.min(minValue, matrix[i][y2 - 1]);
}
// 위쪽
for (let i = y2 - 1; i > y1 - 1; i--) {
matrix[x1 - 1][i] = matrix[x1 - 1][i - 1];
minValue = Math.min(minValue, matrix[x1 - 1][i]);
}
matrix[x1 - 1][y1] = temp;
answer.push(minValue);
}
return answer;
}
'Coding Problem' 카테고리의 다른 글
[프로그래머스] 혼자서 하는 틱택토 (0) | 2025.02.07 |
---|---|
[프로그래머스] PCCP - 석유 시추 (0) | 2025.02.05 |
[프로그래머스] 카카오 - 길 찾기 게임 (0) | 2025.02.03 |
[프로그래머스] 카카오 - 경주로 건설 (0) | 2025.02.02 |
[프로그래머스] 카카오 - 수식 최대화 (0) | 2025.02.01 |