2024. 9. 15. 14:19ㆍAlgorithm
문제 설명
두 개의 단어 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 |
정답
다른 bfs 풀이방식과 비슷하지만 한 가지 실수한 조건이 문제의 단어 길이 조건은 3 ~ 10이다.
check 메서드에서 글자 중복 확인을 처음에는 ==을 이용해 동일한 개수를 세는 방식을 2로 고정했다가 틀렸다. ==을 이용한 풀이는 start 혹은 end의 길이의 -1 값을 이용해 비교해야 정답을 맞힐 수 있다. 단어 길이가 3이 아닌 10까지의 유동 길이를 가지기 때문이다. 그래서 동일한 개수를 세는 방식이 아닌 다른 개수를 세는 방식으로 바꾸면 1 값을 고정으로 사용할 수 있다.
import java.util.*;
class Word {
String word;
int count;
public Word(String word, int count) {
this.word = word;
this.count = count;
}
}
class Solution {
static boolean[] visited;
public int solution(String begin, String target, String[] words) {
int answer = 0;
if (!Arrays.asList(words).contains(target)) {
return 0;
}
for (int i = 0; i < words.length; i++) {
answer = bfs(begin, target, words);
}
return answer;
}
// 이미 안되는건 걸렀으니깐 최단 경로로 단어 변환 수 세기
static int bfs(String begin, String target, String[] words) {
Queue<Word> queue = new LinkedList<>();
queue.offer(new Word(begin, 0));
visited = new boolean[words.length];
while (!queue.isEmpty()) {
Word data = queue.poll();
if (data.word.equals(target)) {
return data.count;
}
for (int i = 0; i < words.length; i++) {
// Word.word와 1개 다른 값들을 주입 = true 반환
if (!visited[i] && check(data.word, words[i])) {
queue.offer(new Word(words[i], data.count + 1));
visited[i] = true;
}
}
}
return 0;
}
static boolean check(String start, String end) {
int cnt = 0;
for (int i = 0; i < start.length(); i++) {
if (start.charAt(i) != end.charAt(i)) {
cnt++;
}
}
// 값이 1라면 변환 가능한 단어
return cnt == 1 ? true : false;
}
}
'Algorithm' 카테고리의 다른 글
[2294 - JAVA] 동전 2 (1) | 2024.10.06 |
---|---|
[프로그래머스 - JAVA] 양궁대회 (0) | 2024.09.22 |
[프로그래머스 - JAVA] 다리를 지나는 트럭 (0) | 2024.08.31 |
[프로그래머스 - JAVA] 전력망을 둘로 나누기 (0) | 2024.08.29 |
[프로그래머스 - JAVA] 택배 배달과 수거하기 (0) | 2024.08.19 |