문제
https://www.acmicpc.net/problem/16927
N x M 크기의 2차원 배열의 모든 레이어를 반시계 방향으로 R번 돌렸을 때의 결과를 구해야 한다.
A[1][1] ← A[1][2] ← A[1][3] ← A[1][4] ← A[1][5]
↓ ↑
A[2][1] A[2][2] ← A[2][3] ← A[2][4] A[2][5]
↓ ↓ ↑ ↑
A[3][1] A[3][2] → A[3][3] → A[3][4] A[3][5]
↓ ↑
A[4][1] → A[4][2] → A[4][3] → A[4][4] → A[4][5]
- 2 ≤ N, M ≤ 300
- 1 ≤ R ≤ 109
- min(N, M) mod 2 = 0
- 1 ≤ 배열의 원소 ≤ 108
풀이
배열의 레이어 별로 정보를 List에 선형으로 저장한다.
담긴 List의 값에 `R`만큼 더해주면 다음 위치가 나오게 된다. `R`의 범위가 1,000,000,000로 매우 크므로 레이어의 크기를 기준으로 모듈로 연산을 적용해주었다. (크기마다 위치가 반복되므로)
R번 회전했을 때의 인덱스가 레이어의 크기를 벗어날 수 있으므로 크기만큼 모듈로 연산을 적용한다.
코드
import java.io.*;
import java.util.*;
public class Main {
static int n, m, r;
static int[][] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
r = Integer.parseInt(st.nextToken());
arr = new int[n][m];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int[][] result = rotateLayers();
for (int[] row : result) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
static int[][] rotateLayers() {
int[][] result = new int[n][m];
int layers = Math.min(n, m) / 2;
for (int layer = 0; layer < layers; layer++) {
int top = layer; int bottom = n - 1 - layer;
int left = layer; int right = m - 1 - layer;
List<Integer> list = new ArrayList<>();
// 위, 오른쪽, 아래, 왼쪽
for (int j = left; j <= right; j++)
list.add(arr[top][j]);
for (int i = top + 1; i < bottom; i++)
list.add(arr[i][right]);
for (int j = right; j >= left; j--)
list.add(arr[bottom][j]);
for (int i = bottom - 1; i > top; i--)
list.add(arr[i][left]);
int length = list.size();
int rotation = r % length;
int idx = 0;
for (int j = left; j <= right; j++)
result[top][j] = list.get((idx++ + rotation) % length);
for (int i = top + 1; i < bottom; i++)
result[i][right] = list.get((idx++ + rotation) % length);
for (int j = right; j >= left; j--)
result[bottom][j] = list.get((idx++ + rotation) % length);
for (int i = bottom - 1; i > top; i--)
result[i][left] = list.get((idx++ + rotation) % length);
}
return result;
}
}'Problem Solving > BOJ' 카테고리의 다른 글
| [BOJ/Java] 1863: 스카이라인 쉬운거 (0) | 2025.06.17 |
|---|---|
| [BOJ/Java] 16236: 아기 상어 (1) | 2025.06.14 |
| [BOJ/Java] 14891: 톱니바퀴 (1) | 2025.06.11 |
| [BOJ/Java] 17143: 낚시왕 (0) | 2025.06.11 |
| [BOJ/Java] 17144: 미세먼지 안녕! (3) | 2025.06.10 |
