https://www.acmicpc.net/problem/14891
접근 방법
기존에 4개의 톱니바퀴를 어떤 자료구조로 저장할지 고민하고, 이동시키는게 상대적으로 편한 리스트를 고민했으나 다른 사람들의 풀이를 참고하여 2차원배열이 훨씬 편한것을 확인했다. 시계 방향, 반시계 방향도 생각보다 이동시키기 쉽다.
움직이는 톱니바퀴를 찾고, 해당 톱니바퀴의 왼쪽 및 오른쪽을 순회하며 움직이는 경우엔 현재 방향에서 -1을 곱해주고 아닌 경우엔 멈췄다는 의미이므로 탐색을 중지했다. 4개 톱니바퀴의 이동 방향을 저장해둔 다음에, 시계 방향 및 반시계 방향에 따라서 재배열을 진행하면 되는 문제였다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class boj14891 {
static int [][] wheels = new int[4][8];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < 4; i++) {
String input = br.readLine();
for(int j = 0; j < 8; j++) {
wheels[i][j] = input.charAt(j) - '0';
}
}
int k = Integer.parseInt(br.readLine());
for(int i = 0; i < k; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int target = Integer.parseInt(st.nextToken());
int dir = Integer.parseInt(st.nextToken());
target -= 1;
int [] arr = new int[4];
arr[target] = dir;
for(int j = target - 1; j >= 0; j--) { // 왼쪽 방향으로
if (wheels[j+1][6] != wheels[j][2]) { // 만약에 방향이 다르다면 반대로 회전
arr[j] = arr[j+1] * -1;
}
else break; // 움직이지 않는다면 고정
}
for(int j = target; j < 3; j++) {
if (wheels[j][2] != wheels[j+1][6]) {
arr[j+1] = arr[j] * -1;
}
else break;
}
for(int j = 0; j < 4; j++) {
if (arr[j] == 1) wheels[j] = turnRight(j);
else if (arr[j] == -1) wheels[j] = turnLeft(j);
}
// for(int j = 0; j < 4; j++) {
// for(int t = 0; t < 8; t++) {
// System.out.print(wheels[j][t]);
// }
// System.out.println();
// }
}
System.out.println(getScore());
}
public static int getScore() {
int score = 0;
if (wheels[0][0] == 1) score += 1;
if (wheels[1][0] == 1) score += 2;
if (wheels[2][0] == 1) score += 4;
if (wheels[3][0] == 1) score += 8;
return score;
}
// 01111101
// 1 0111110
public static int[] turnRight(int target) { // 1일때 시계방향 회전
int[] tmp = new int[8];
for(int i = 1; i < 8; i++) { //
tmp[i] = wheels[target][i-1];
}
tmp[0] = wheels[target][7];
return tmp;
}
// 01111101
// 1111101 0
public static int[] turnLeft(int target) { // -1일때 역방향 회전
int[] tmp = new int[8];
for(int i = 0; i < 7; i++) {
tmp[i] = wheels[target][i+1];
}
tmp[7] = wheels[target][0];
return tmp;
}
}
'Algorithm > 백준' 카테고리의 다른 글
2차원 배열에서 회전 (0) | 2025.06.22 |
---|---|
연산자 끼워넣기, 스타트와 링크 (1) | 2025.06.03 |
[백준] 감시 (1) | 2025.05.25 |
boj21939: 문제 추천 시스템 Version 1 (1) | 2025.05.15 |
boj13904: 과제 (2) | 2025.05.15 |