[JAVA] 프로그래머스 : 단어 변환
Updated:
단어 변환
문제 설명
문제 설명
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.
1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
2. words에 있는 단어로만 변환할 수 있습니다.
예를 들어 begin이 “hit”, target가 “cog”, words가 [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]라면 “hit” -> “hot” -> “dot” -> “dog” -> “cog”와 같이 4단계를 거쳐 변환할 수 있습니다.
두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.
제한사항
- 각 단어는 알파벳 소문자로만 이루어져 있습니다.
- 각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
- words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
- begin과 target은 같지 않습니다.
- 변환할 수 없는 경우에는 0를 return 합니다.
입출력 예
| begin | target | words | return |
|---|---|---|---|
| “hit” | “cog” | [“hot”, “dot”, “dog”, “lot”, “log”, “cog”] | 4 |
| “hit” | “cog” | [“hot”, “dot”, “dog”, “lot”, “log”] | 0 |
입출력 예 설명
예제 #1 문제에 나온 예와 같습니다.
예제 #2 target인 “cog”는 words 안에 없기 때문에 변환할 수 없습니다.
문제 풀이 @DFS
코드
import java.util.*;
class Solution {
int min = 987654321;
public void dfs(String target, List<String> list, int idx, int cnt, boolean[] visited){
if(list.get(idx).equals(target)){ //마감
min = min > cnt ? cnt : min;
return;
}
for(int i=0; i< list.size() ; i++){
if(i == idx || visited[i]) //이미 거쳐온 단어거나 나일때
continue;
int diff=0;
for(int j=0;j<list.get(i).length();j++){ //문자 1개만 다른 단어 확인
if(list.get(idx).charAt(j) != list.get(i).charAt(j)){
if(diff == 0)
diff++;
else{
diff = 0;
break;
}
}
}
if(diff == 1){ //1문자만 다른 단어라면
visited[i] = true;
dfs(target, list, i, cnt+1, visited); //다음 단어 찾기
visited[i] = false;
}
}
}
public int solution(String begin, String target, String[] words) {
int answer = 0;
boolean[] visited = new boolean[words.length+1];
List<String> list = new ArrayList<>(Arrays.asList(words));
/*target이 배열에 없는 경우*/
if(!list.contains(target))
return 0;
/*begin을 list에 넣어서 확인*/
list.add(0, begin);
visited[0] = true;
dfs(target, list, 0, 0, visited);
return (min==987654321 ? 0 : min);
}
}
풀이 방법
DFS를 이용하여 쉽게 풀 수 있는 문제다.
words에 target이 없을 경우 확인하지 않고 0을 반환하면 시간이 더 짧아진다.
사용 문법 정리
-
List<String> list = new ArrayList<>(Arrays.asList(words));array → arrayList로 만들 때 사용하는 문법. new를 해주지 않으면 get, set만 가능한 list가 된다.
-
list.contains(target)list에 해당 String이 있는지 확인하는 문법.
-
Arrays.binarySearch(words, target)array에서 해당 String이 있는지 찾는 문법. 다만 없을 경우 exception이 나오기 때문에 try catch문이 필요하다.

Leave a comment