알고리즘
백준 14891번 톱니바퀴 (JAVA)
박카스마시며코딩
2022. 3. 24. 15:29
https://www.acmicpc.net/problem/14891
14891번: 톱니바퀴
첫째 줄에 1번 톱니바퀴의 상태, 둘째 줄에 2번 톱니바퀴의 상태, 셋째 줄에 3번 톱니바퀴의 상태, 넷째 줄에 4번 톱니바퀴의 상태가 주어진다. 상태는 8개의 정수로 이루어져 있고, 12시방향부터
www.acmicpc.net
저는 재귀적인 방법으로 문제를 해결하였습니다.
재귀적인 방법으로 다음 인덱스의 LEFT와 현재 RIGHT가 같으면 다음 인덱스의 톱니바퀴를 현재의 반대 방향으로 돌리게 하였고 반대 반향도 똑같이 하였습니다.
개인적으로 TOP , RIGHT , LEFT를 불변변수로 선언하고 코드를 짜는게 괜찮은 것 같습니다. 지금 방법으로 했을 때 틀린 부분을 찾기 보다 쉬울 것이라 생각합니다.
package BOJ.ETC;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.function.Function;
public class BOJ_14891 {
private static final int TOP = 0;
private static final int RIGHT = 2;
private static final int LEFT = 6;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Function<String,Integer> stoi = Integer::parseInt;
LinkedList<Integer>[] list = new LinkedList[4];
for(int i = 0 ; i < 4 ; i++){
list[i] = new LinkedList<>();
String command = br.readLine();
for(int j = 0 ; j < 8 ; j++){
int now = command.charAt(j)-'0';
list[i].offerLast(now);
}
}
int m = stoi.apply(br.readLine());
for(int i = 0 ; i < m ; i++){
boolean[] visited = new boolean[4];
String[] command = br.readLine().split(" ");
int location = stoi.apply(command[0])-1;
int dir = stoi.apply(command[1]);
rotation(location,dir,list,visited);
}
int result = 0;
for(int i = 0 ; i < 4 ; i++){
// System.out.println(list[i]);
if(list[i].get(TOP) == 1){
if(i == 0){
result += 1;
}else if(i == 1){
result += 2;
}else if(i == 2){
result += 4;
}else if(i == 3){
result += 8;
}
}
}
System.out.println(result);
}
private static void rotation(int location, int dir , LinkedList<Integer>[] list,boolean[] visited){
LinkedList<Integer> nowList = list[location];
visited[location] = true;
if(location + 1 < 4 && !visited[location + 1] && nowList.get(RIGHT) != list[location + 1].get(LEFT)){
rotation(location+1,-dir,list,visited);
}
if(location - 1 >= 0 && !visited[location - 1] && nowList.get(LEFT) != list[location - 1].get(RIGHT)){
rotation(location-1,-dir,list,visited);
}
if(dir == 1){
int last = nowList.pollLast();
nowList.offerFirst(last);
}else{
int first = nowList.pollFirst();
nowList.offerLast(first);
}
}
}