알고리즘

백준 1343번 폴리오미노 (JAVA)

박카스마시며코딩 2024. 1. 17. 23:13

https://www.acmicpc.net/problem/1343

 

1343번: 폴리오미노

첫째 줄에 사전순으로 가장 앞서는 답을 출력한다. 만약 덮을 수 없으면 -1을 출력한다.

www.acmicpc.net

 

저는 DP를 이용하였습니다.

해당 depth부터 연속적으로 .이 몇개 있는지를 판단하여 AAAA 또는 BB를 넣을지를 판단하여 dfs를 통해 모든 경우를 찾았습니다. 이때 중복되는 경우는 다시 계산하지 안도록 하기위해 DP를 이용하였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BOJ_1343 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String command = br.readLine();
        String result = cal(0,command);
        System.out.println(result);
    }
    private static final String NOT_FOUND = "-1";
    private static String cal(int depth, String command) {
        if(depth == command.length()){
            return "";
        }
        if(command.charAt(depth) == '.'){
            String temp = cal(depth+1,command);
            if(temp.equals(NOT_FOUND)){
                return NOT_FOUND;
            }
            return '.'+temp;
        }
        boolean[] can = new boolean[4];
        boolean flag = true;
        for(int i = 0 ; i < 4 && depth + i < command.length(); i++){
            if(command.charAt(depth+i) == '.'){
                flag = false;
            }
            can[i] = flag;
        }
        String result = NOT_FOUND;
        if(can[1]){
            String temp = cal(depth+2,command);
            if(!temp.equals(NOT_FOUND)){
                result = "BB" + temp;
            }
        }
        if(can[3]){
            String temp = cal(depth+4,command);
            if(!temp.equals(NOT_FOUND)){
                result = "AAAA" + temp;
            }
        }
        return result;
    }

}

'알고리즘' 카테고리의 다른 글

백준 1806번 부분합 (JAVA)  (1) 2024.01.19
백준 14916번 거스름돈 (JAVA)  (0) 2024.01.16
백준 2217번 로프 (JAVA)  (0) 2024.01.15
백준 1758번 알바생 강호 (JAVA)  (1) 2024.01.14
백준 2164번 카드2 (JAVA)  (1) 2024.01.13