문제 출처 :
https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제설명:
두 개의 단어 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)
주어진 문자에서 (begin) words 배열에 들어있으면서 알파벳 하나만 다른 경우(word)를 찾고,
다시 같은 조건을 만족하는 경우를 계속 찾으면서 target과 같은 단어가 되는 최소 변환 수를 찾는다.
class Solution {
private boolean visited[];
private int answer = 51;
public int solution(String begin, String target, String[] words) {
visited = new boolean[words.length];
for (int i=0; i<words.length; i++) {
//변환 가능 단어 찾기
if (compare(begin, words[i]) == 1) {
//dfs 탐색
visited[i] = true;
dfs(1, i, target, words);
}
}
return answer == 51 ? 0 : answer;
}
public void dfs(int cnt, int curIdx, String target, String[] words) {
//dfs 종료조건 (target 이랑 같을시)
if (words[curIdx].equals(target)) {
answer = Math.min(answer, cnt);
return;
}
for(int i = 0; i < words.length; i++) {
// 탐색 가능 여부 체크
if (!visited[i] && compare(words[curIdx], words[i]) == 1) {
visited[i] = true;
dfs(cnt+1, i, target, words);
visited[i] = false;
}
}
}
public int compare(String str1, String str2) {
int n = 0;
for (int i=0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
n++;
}
}
return n;
}
}
(BFS) 풀이 :
import java.util.*;
class Solution {
private boolean visited[];
private int answer = 0;
public int solution(String begin, String target, String[] words) {
visited = new boolean[words.length];
answer = bfs(begin, target, words);
return answer;
}
public int bfs(String begin, String target, String[] words) {
Queue<String> q = new LinkedList<>();
q.add(begin);
while(!q.isEmpty()) {
for (int i = 0; i < q.size(); i++) {
String curWord = q.poll();
if (curWord.equals(target)) { // 종료조건
return answer;
}
for (int j = 0; j < words.length; j++) {
if (!visited[j] && compare(curWord,words[j]) == 1) {
visited[j] = true;
q.add(words[j]);
}
}
}
//큐의 개수만큼 확인을 한 경우 (한 단계가 끝) 단어 변환 횟수도 +1
answer++;
}
return 0;
}
public int compare(String str1, String str2) {
int n = 0;
for (int i=0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
n++;
}
}
return n;
}
}
'알고리즘 > 프로그래머스 문제풀이' 카테고리의 다른 글
프로그래머스 LV1 > 체육복 (자바/JAVA) - 그리디 알고리즘 (0) | 2024.10.18 |
---|---|
프로그래머스 lv3 > 네트워크 (DFS) (JAVA/자바) (1) | 2024.10.16 |
프로그래머스 lv2 > 게임 맵 최단거리 (0) | 2024.10.16 |
프로그래머스 lv2 > 피보나치 수 (JAVA/자바) (0) | 2024.10.15 |
프로그래머스 lv2 > 방문 길이 (자바/JAVA) (7) | 2024.10.10 |