https://www.acmicpc.net/problem/1343
1343번: 폴리오미노
첫째 줄에 사전순으로 가장 앞서는 답을 출력한다. 만약 덮을 수 없으면 -1을 출력한다.
www.acmicpc.net
저는 dfs를 통해 문제를 해결하였습니다.
각각의 문자를 보고 .이라면 바로 다음으로, 그것이 아니라면 해당 문자부터 4개중에 .이 있는지를 확인하고, 이 값을 토대로 dfs를 진행하였습니다. 2번째 문자까지 없다면 BB 4번째 문자까지 . 이 없다면 AAAA를 하여 문제를 해결하였습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BOJ_1343 {
private static final String NOT_FOUND = "-1";
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 String cal(int depth, String command, String now) {
if(command.length() <= depth){
return now;
}
if(command.charAt(depth) == '.'){
return cal(depth+1,command,now+".");
}
String result = NOT_FOUND;
boolean[] isX = new boolean[4];
Arrays.fill(isX,true);
boolean flag = true;
for(int i = 0 ; i < 4; i++){
if(depth+i >= command.length()){
break;
}
char ch = command.charAt(depth+i);
if(ch == '.'){
flag = false;
}
isX[i] = flag;
}
if(isX[1] && depth+1 < command.length()){
String temp = cal(depth+2,command,now+"BB");
if(result.equals(NOT_FOUND)){
result = temp;
}else if(result.compareTo(temp) > 0){
result = temp;
}
}
if(isX[3] && depth+3 < command.length()){
String temp = cal(depth+4,command,now+"AAAA");
if(result.equals(NOT_FOUND)){
result = temp;
}else if(result.compareTo(temp) > 0){
result = temp;
}
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 2238번 경매 (JAVA) (0) | 2023.10.19 |
---|---|
백준 1500번 최대 곱 (JAVA) (1) | 2023.10.18 |
백준 4396번 지뢰 찾기 (JAVA) (0) | 2023.10.16 |
백준 1817번 짐 챙기는 숌 (JAVA) (0) | 2023.10.16 |
프로그래머스 세 개의 구분자 (JAVA) (1) | 2023.10.14 |