From daa5a65e10591999cc321445d608d1c46ddfc6aa Mon Sep 17 00:00:00 2001 From: ShineCorine Date: Thu, 11 Apr 2024 15:57:28 +0900 Subject: [PATCH] =?UTF-8?q?[solved]=20PRG=5F=EB=A0=88=EB=B2=A82=5F?= =?UTF-8?q?=EC=88=AB=EC=9E=90=20=EB=B3=80=ED=99=98=ED=95=98=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Jongmin_solved.java" | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 "Week 17/PRG_\353\240\210\353\262\2502_\353\222\244\354\227\220 \354\236\210\353\212\224 \355\201\260 \354\210\230 \354\260\276\352\270\260/Jongmin_solved.java" diff --git "a/Week 17/PRG_\353\240\210\353\262\2502_\353\222\244\354\227\220 \354\236\210\353\212\224 \355\201\260 \354\210\230 \354\260\276\352\270\260/Jongmin_solved.java" "b/Week 17/PRG_\353\240\210\353\262\2502_\353\222\244\354\227\220 \354\236\210\353\212\224 \355\201\260 \354\210\230 \354\260\276\352\270\260/Jongmin_solved.java" new file mode 100644 index 0000000..2249c71 --- /dev/null +++ "b/Week 17/PRG_\353\240\210\353\262\2502_\353\222\244\354\227\220 \354\236\210\353\212\224 \355\201\260 \354\210\230 \354\260\276\352\270\260/Jongmin_solved.java" @@ -0,0 +1,49 @@ +import java.util.*; +class Solution { + public int solution(int x, int y, int n) { + int answer = 0; + + Boolean[] visited = new Boolean[1_000_001]; + Arrays.fill(visited, Boolean.FALSE); // 이건 검색으로 알아낸건데 굳이 해줄 필요는 없는 것 같습니다. + + // 이번에도 큐를 활용한 DFS방식으로 풀면 좋겠다는 생각이 들었습니다. + // 현재 숫자와 현재까지의 연산 횟수를 저장하는 리스트를 큐에 넣어주고 + // 큐에서 하나씩 빼면서 연산을 진행합니다. + // 진행하다 원하는 결과가 나오면, 그게 가장 적은 횟수로 원하는 숫자를 만드는 것이므로 + // 바로 결과를 리턴해줍니다. 만약 해당하는 값이 없다면 -1을 리턴해줍니다. + + Queue> queue = new ArrayDeque<>(); + queue.offer(List.of(x, 0)); + visited[x] = true; + int count = 0; + + while(!queue.isEmpty()){ + List element = queue.poll(); + + int c = element.get(0); + count = element.get(1); + if(c == y ) return count; + count++; + + int nc = c+n; + + if(nc <= y && !visited[nc]){ + visited[nc] = true; + queue.offer(List.of(nc, count)); + + } + nc = c*2; + if(nc <= y && !visited[nc]){ + visited[nc] = true; + queue.offer(List.of(nc, count)); + } + + nc = c*3; + if(nc <= y && !visited[nc]){ + visited[nc] = true; + queue.offer(List.of(nc, count)); + } + } + return -1; + } +} \ No newline at end of file