Skip to content

Commit 2201633

Browse files
committed
[level 3] Title: 단어 변환, Time: 0.72 ms, Memory: 79.9 MB -BaekjoonHub
1 parent 7cadc87 commit 2201633

2 files changed

Lines changed: 155 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# [level 3] 단어 변환 - 43163
2+
3+
[문제 링크](https://school.programmers.co.kr/learn/courses/30/lessons/43163)
4+
5+
### 성능 요약
6+
7+
메모리: 79.9 MB, 시간: 0.72 ms
8+
9+
### 구분
10+
11+
코딩테스트 연습 > 깊이/너비 우선 탐색(DFS/BFS)
12+
13+
### 채점결과
14+
15+
정확성: 100.0<br/>합계: 100.0 / 100.0
16+
17+
### 제출 일자
18+
19+
2025년 08월 29일 09:45:02
20+
21+
### 문제 설명
22+
23+
<p>두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.</p>
24+
<div class="highlight"><pre class="codehilite"><code>1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
25+
2. words에 있는 단어로만 변환할 수 있습니다.
26+
</code></pre></div>
27+
<p>예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -&gt; "hot" -&gt; "dot" -&gt; "dog" -&gt; "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.</p>
28+
29+
<p>두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.</p>
30+
31+
<h5>제한사항</h5>
32+
33+
<ul>
34+
<li>각 단어는 알파벳 소문자로만 이루어져 있습니다.</li>
35+
<li>각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.</li>
36+
<li>words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.</li>
37+
<li>begin과 target은 같지 않습니다.</li>
38+
<li>변환할 수 없는 경우에는 0를 return 합니다.</li>
39+
</ul>
40+
41+
<h5>입출력 예</h5>
42+
<table class="table">
43+
<thead><tr>
44+
<th>begin</th>
45+
<th>target</th>
46+
<th>words</th>
47+
<th>return</th>
48+
</tr>
49+
</thead>
50+
<tbody><tr>
51+
<td>"hit"</td>
52+
<td>"cog"</td>
53+
<td>["hot", "dot", "dog", "lot", "log", "cog"]</td>
54+
<td>4</td>
55+
</tr>
56+
<tr>
57+
<td>"hit"</td>
58+
<td>"cog"</td>
59+
<td>["hot", "dot", "dog", "lot", "log"]</td>
60+
<td>0</td>
61+
</tr>
62+
</tbody>
63+
</table>
64+
<h5>입출력 예 설명</h5>
65+
66+
<p>예제 #1<br>
67+
문제에 나온 예와 같습니다.</p>
68+
69+
<p>예제 #2<br>
70+
target인 "cog"는 words 안에 없기 때문에 변환할 수 없습니다.</p>
71+
72+
73+
> 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
static List<Integer>[] edges;
5+
static int n, m;
6+
static String[] ws; // words 저장
7+
static String beginS; // begin 저장
8+
static int beginIdx; // 그래프에서 begin 노드 인덱스 (마지막)
9+
static int targetIdx; // words에서 target의 인덱스
10+
11+
public int solution(String begin, String target, String[] words) {
12+
// target이 words에 없으면 변환 불가
13+
int tIdx = -1;
14+
for (int i = 0; i < words.length; i++) {
15+
if (words[i].equals(target)) {
16+
tIdx = i;
17+
break;
18+
}
19+
}
20+
if (tIdx == -1) return 0;
21+
22+
ws = words;
23+
beginS = begin;
24+
n = words.length + 1; // words + begin
25+
m = begin.length();
26+
beginIdx = n - 1; // begin을 마지막 인덱스로
27+
targetIdx = tIdx;
28+
29+
// 인접 리스트 초기화
30+
edges = new ArrayList[n];
31+
for (int i = 0; i < n; i++) edges[i] = new ArrayList<>();
32+
33+
// 모든 쌍에 대해 간선 연결 (한 글자만 다르면 연결)
34+
for (int i = 0; i < n - 1; i++) {
35+
for (int j = i + 1; j < n; j++) {
36+
String a = getWord(i);
37+
String b = getWord(j);
38+
if (isAdjacent(a, b)) {
39+
edges[i].add(j);
40+
edges[j].add(i);
41+
}
42+
}
43+
}
44+
45+
// BFS로 begin -> target 최단 거리
46+
int[] dist = new int[n];
47+
Arrays.fill(dist, -1);
48+
Queue<Integer> q = new ArrayDeque<>();
49+
dist[beginIdx] = 0;
50+
q.add(beginIdx);
51+
52+
while (!q.isEmpty()) {
53+
int cur = q.poll();
54+
if (cur == targetIdx) return dist[cur];
55+
for (int nxt : edges[cur]) {
56+
if (dist[nxt] == -1) {
57+
dist[nxt] = dist[cur] + 1;
58+
q.add(nxt);
59+
}
60+
}
61+
}
62+
return 0; // 도달 불가
63+
}
64+
65+
// 인덱스에 해당하는 단어 반환: 0..n-2 => words, n-1 => begin
66+
static String getWord(int idx) {
67+
return (idx == n - 1) ? beginS : ws[idx];
68+
}
69+
70+
// 두 단어가 정확히 한 글자만 다른지
71+
static boolean isAdjacent(String a, String b) {
72+
if (a.length() != b.length()) return false;
73+
int diff = 0;
74+
for (int i = 0; i < a.length(); i++) {
75+
if (a.charAt(i) != b.charAt(i)) {
76+
diff++;
77+
if (diff > 1) return false;
78+
}
79+
}
80+
return diff == 1;
81+
}
82+
}

0 commit comments

Comments
 (0)