Tech/Problem Solving
[프로그래머스 - BFS] 단어 변환 (Java)
Bellroute
2020. 4. 23. 15:16
https://programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
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 안에 없기 때문에 변환할 수 없습니다.
접근 방식
bfs로 접근하면 쉽게 풀 수 있는 문제였다.
소스 코드
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
private String[] map;
private boolean[] visited;
private int targetIndex;
private int answer = Integer.MAX_VALUE;
public int solution(String begin, String target, String[] words) {
map = words.clone();
if (!isContain(words, target)) {
return 0;
}
for (int i = 0; i < map.length; i++) {
if (words[i].equals(target)) {
targetIndex = i;
break;
}
}
for (int i = 0; i < map.length; i++) {
if (isOnlyOneDifferentCharacter(begin, map[i])) {
visited = new boolean[map.length];
visited[i] = true;
bfs(i);
}
}
return answer;
}
private void bfs(int index) {
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(index, 1));
while (!queue.isEmpty()) {
Point point = queue.poll();
if (map[point.index].equals(map[targetIndex])) {
answer = Math.min(answer, point.depth);
return;
}
for (int i = 0; i < map.length; i++) {
if (!visited[i] && isOnlyOneDifferentCharacter(map[point.index], map[i])) {
visited[i] = true;
queue.add(new Point(i, point.depth + 1));
}
}
}
}
private boolean isOnlyOneDifferentCharacter(String now, String word) {
int count = 0;
for (int i = 0; i < now.length(); i++) {
if (now.charAt(i) != word.charAt(i)) {
count++;
}
}
return count == 1;
}
private boolean isContain(String[] words, String target) {
for (String word : words) {
if (word.equals(target)) {
return true;
}
}
return false;
}
private class Point {
private int index;
private int depth;
public Point(int index, int depth) {
this.index = index;
this.depth = depth;
}
}
}
반응형