https://www.acmicpc.net/problem/14395
14395번: 4연산
첫째 줄에 정수 s를 t로 바꾸는 방법을 출력한다. s와 t가 같은 경우에는 0을, 바꿀 수 없는 경우에는 -1을 출력한다. 가능한 방법이 여러 가지라면, 사전 순으로 앞서는 것을 출력한다. 연산의 아
www.acmicpc.net
저는 구현을 통해 문제를 해결하였습니다.
방문체크는 그 숫자로 하였고, /는 0일때 하면 안되기 때문에 지금 숫자가 0이라면 continue를 통해 안하게 구현하였습니다.
시작 숫자와 끝 숫자가 같다면 처음부터 0을 리턴하도록하고 못구한다면 -1을 리턴하였습니다.
package BOJ.bfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_14395 {
private static class Node{
long num;
String operations;
public Node(long num, String operations) {
this.num = num;
this.operations = operations;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Function<String,Integer> stoi = Integer::parseInt;
int startNum = stoi.apply(st.nextToken());
int endNum = stoi.apply(st.nextToken());
String result = bfs(startNum,endNum);
System.out.println(result);
}
private static char[] OPERATION = {'*','+','-','/'};
private static String bfs(int startNum, int endNum) {
if(startNum == endNum){
return "0";
}
Queue<Node> q = new LinkedList<>();
q.offer(new Node(startNum,"") );
Set<Long> visited = new HashSet<>();
while(!q.isEmpty()){
Node now = q.poll();
if(now.num == endNum){
return now.operations;
}
long nextNum = now.num * now.num;
if(!visited.contains(nextNum)){
visited.add(nextNum);
q.offer(new Node(nextNum,now.operations+"*"));
}
nextNum = now.num + now.num;
if(!visited.contains(nextNum)){
visited.add(nextNum);
q.offer(new Node(nextNum,now.operations+"+"));
}
nextNum = now.num - now.num;
if(!visited.contains(nextNum)){
visited.add(nextNum);
q.offer(new Node(nextNum,now.operations+"-"));
}
if(now.num == 0){
continue;
}
nextNum = now.num / now.num;
if(!visited.contains(nextNum)){
visited.add(nextNum);
q.offer(new Node(nextNum,now.operations+"/"));
}
}
return "-1";
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 평균 구하기 (JAVA) (0) | 2022.09.28 |
---|---|
백준 19538번 루머 (JAVA) (0) | 2022.09.27 |
프로그래머스 PCCP 모의고사 4번 (JAVA) (0) | 2022.09.25 |
프로그래머스 PCCP 모의고사 2번 (JAVA) (1) | 2022.09.24 |
프로그래머스 PCCP 모의고사 1번 (JAVA) (0) | 2022.09.23 |