문제
https://programmers.co.kr/learn/courses/30/lessons/77485
코딩테스트 연습 - 행렬 테두리 회전하기
6 6 [[2,2,5,4],[3,3,6,6],[5,1,6,3]] [8, 10, 25] 3 3 [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] [1, 1, 5, 3]
programmers.co.kr
문제에서 요구하는대로 배열을 회전시키기 위해서는
해당 배열을 다음과 같이 쪼개서 배열을 회전시켜야한다.
구간을 4개로 나눈 다음에 파랑색 구간 -빨강색 구간 - 보라색 구간 - 연두색 구간 순으로 큐에 담아주었다.
그런다음 큐에 담아놓은 값들을 4개의 구간에 맞게 각각 갱신시켜주었다.
값을 갱신시키는 과정에서 가장 작은 값을 계속 체크해주었다.
코드
import java.util.*;
class Solution {
static int[] ans;
static int[][] queries;
static int[][] arr;
public static int rotate(int y1, int x1, int y2, int x2) {
Queue<Integer> q = new LinkedList<>();
//1번째 구간
for(int i = x1; i < x2; i++) {
q.add(arr[y1][i]);
}
//2번째 구간
for(int i = y1; i < y2; i++) {
q.add(arr[i][x2]);
}
//3번째 구간
for(int i = x2; i > x1; i--) {
q.add(arr[y2][i]);
}
//4번째 구간
for(int i = y2; i > y1; i--) {
q.add(arr[i][x1]);
}
int minValue = Integer.MAX_VALUE;
while(q.size() > 0) {
for(int i = x1; i < x2; i++) {
minValue = Math.min(minValue, q.peek());
arr[y1][i+1] = q.poll();
}
for(int i = y1; i < y2; i++) {
minValue = Math.min(minValue, q.peek());
arr[i+1][x2] = q.poll();
}
for(int i = x2; i > x1; i--) {
minValue = Math.min(minValue, q.peek());
arr[y2][i-1] = q.poll();
}
for(int i = y2; i > y1; i--) {
minValue = Math.min(minValue, q.peek());
arr[i-1][x1] = q.poll();
}
}
return minValue;
}
public int[] solution(int rows, int columns, int[][] queries) {
ans = new int[queries.length];
arr = new int[rows][columns];
int num = 1;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
arr[i][j] = num++;
}
}
for(int i = 0; i < queries.length; i++) {
ans[i] = rotate(queries[i][0] - 1, queries[i][1] - 1, queries[i][2] - 1, queries[i][3] - 1);
}
return ans;
}
}
'개발 > 알고리즘' 카테고리의 다른 글
백준 3584 가장 가까운 공통 조상 C++ (0) | 2021.07.19 |
---|---|
백준 2533 사회망 서비스(SNS) Tree DP / C++ (0) | 2021.07.19 |
프로그래머스 순위검색 C++ (0) | 2021.07.02 |
백준 2193 이친수 (0) | 2021.06.29 |
백준 10844 쉬운 계단 수 (0) | 2021.06.29 |