백준 14891번 톱니바퀴 JAVA

YB·2025년 2월 13일

링크텍스트

설명

시간복잡도: O(N), 공간복잡도: O(1)

코드

import java.util.*;
import java.io.*;

class Main {
	public static void main (String[] args) throws IOException {
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    
	    int [][] wheel = new int[5][8];
	    
	    for(int i=1;i<5;i++){
			String s = br.readLine();
	        for(int j=0;j<8;j++){
	            wheel[i][j]= s.charAt(j) - '0';
	        }
	    }

		int k = Integer.parseInt(br.readLine());

		for(int i=0;i<k;i++){
			StringTokenizer st = new StringTokenizer(br.readLine());
			int wheelNum = Integer.parseInt(st.nextToken());
			int direction = Integer.parseInt(st.nextToken());

			int [] rotate = new int[5]; 
			rotate[wheelNum] = direction;

			check(wheel, rotate, wheelNum);

			for(int j=1;j<5;j++){
                if(rotate[j] != 0){
                    rotateWheel(wheel[j], rotate[j]);
                }
            }
        }

		int score = 0;
        if (wheel[1][0] == 1) score += 1;
        if (wheel[2][0] == 1) score += 2;
        if (wheel[3][0] == 1) score += 4;
        if (wheel[4][0] == 1) score += 8;

        System.out.println(score);
	}
	
	public static void check(int[][] wheel, int[] rotate, int num){

		for(int i=num;i>1;i--){
			if(wheel[i][6] != wheel[i-1][2]){
				rotate[i-1] = - rotate[i];
			}else
				break;
		}

		for(int i=num;i<4;i++){
            if(wheel[i][2] != wheel[i + 1][6]){
                rotate[i + 1] = -rotate[i];
            }else{
            	break; 
            }
        }
	}

	public static void rotateWheel(int[] wheel, int direction){
        if(direction == 1){
            int temp = wheel[7];
            for(int i=7;i>0;i--){
                wheel[i] = wheel[i - 1];
            }
            wheel[0] = temp;
        }else if(direction == -1){
            int temp = wheel[0];
            for (int i=0;i<7;i++){
                wheel[i] = wheel[i + 1];
            }
            wheel[7] = temp;
        }
    }
}

profile
안녕하세요

0개의 댓글