
-Code
import java.util.*;
class Solution {
public int solution(int x, int y, int n) {
return BFS(x, y, n);
}
private static int BFS (int start, int target, int num) {
boolean[] visited = new boolean[target + 1];
int answer = 0;
Deque<Integer> deque = new ArrayDeque<>();
deque.addLast(start);
while (!deque.isEmpty()) {
// 3개 연산중 하나를 선택해서 맞는게 반환되므로
// 3개 연산이 동시에 돌아가야해서 deque의 사이즈 만큼 반복
int size = deque.size();
for (int i = 0; i < size; i++) {
int now = deque.pollFirst();
// 현재 값이 타겟과 같으면 결과 반환
if (now == target) {
return answer;
}
// 3가지 계산
int[] calcs = {now + num, now * 2, now * 3};
for (int calc : calcs) {
if (calc <= target && !visited[calc]) {
visited[calc] = true;
deque.addLast(calc);
}
}
}
// 3가지 연산을 다 담으면 +1
answer++;
}
return -1;
}
}
3개의 연산이 같은 횟수에서 일어나야 하는데 처음에 하나하나 계산 후 answer++을 해줘서 다른 결과를 냈습니다. 이 부분에 대해서 깨닫지 못해서 틀렸었고 알게 된 후에 예제는 다 맞았지만 visited를 안 쓰고 하니 메모리 초과가 되어서 해당 부분을 추가해 해결했습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 1904번 01타일 (0) | 2026.01.07 |
|---|---|
| [백준/Java] 1753번 최단경로 (0) | 2026.01.07 |
| [백준/Java] 35097번 2025 (0) | 2026.01.07 |
| [백준/Java] 2468번 안전 영역 (0) | 2026.01.06 |
| [프로그래머스/Java] 피로도 (0) | 2026.01.06 |