Skip to content

Commit bdaca64

Browse files
committed
[level 3] Title: 단어 변환, Time: 0.39 ms, Memory: 10.2 MB -BaekjoonHub
1 parent a225c18 commit bdaca64

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
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+
메모리: 10.2 MB, 시간: 0.39 ms
8+
9+
### 구분
10+
11+
코딩테스트 연습 > 깊이/너비 우선 탐색(DFS/BFS)
12+
13+
### 채점결과
14+
15+
정확성: 100.0<br/>합계: 100.0 / 100.0
16+
17+
### 제출 일자
18+
19+
2025년 03월 07일 19:37:11
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: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from collections import deque
2+
3+
def check(w1, w2):
4+
cnt = 0
5+
for a, b in zip(w1, w2):
6+
if a != b:
7+
cnt += 1
8+
return cnt == 1
9+
10+
def solution(begin, target, words):
11+
if target not in words:
12+
return 0
13+
14+
q = deque([(begin, 0)])
15+
visited = set()
16+
17+
while q:
18+
cur, step = q.popleft()
19+
20+
if cur == target:
21+
return step
22+
23+
for word in words:
24+
if word not in visited and check(cur, word):
25+
visited.add(word)
26+
q.append((word, step+1))
27+
return 0

0 commit comments

Comments
 (0)