문제 풀이에 대한 오류 지적 및 개선 방향 제시는 항상 환영합니다.
알고리즘 문제를 엄청 잘 풀고 막 문제 보자마자 아 이거네 쉽네 ㅎㅎ 이렇게 푸는 입장이 아니라서
그 어떤 문제에 대한 비판 지적 방향 제시는 언제나 감사하게 받겠습니다.
이 문제가 올라가는 저장소 : https://github.com/hwk0911/Junit-TDD
문제 설명
두 개의 단어 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 안에 없기 때문에 변환할 수 없습니다.
solution
public class Programmers_DFS_BFS_3 {
int count;
public int solution(String begin, String target, String[] words) {
count = words.length + 1;
backTracking(words,begin,target,0, new boolean[words.length]);
int answer = 0;
if(count != words.length + 1) {
answer = this.count;
}
return answer;
}
public void backTracking (String[] words, String now, String target, int tempCount, boolean[] visited) {
if(target.equals(now)) {
count = Math.min(count, tempCount);
return;
}
else if(tempCount > count) {
return;
}
for(int index = 0, size = words.length ; index < size ; ++index) {
if(!visited[index] && checkWords(now, words[index])) {
visited[index] = !visited[index];
backTracking(words, words[index], target, tempCount + 1, visited);
visited[index] = !visited[index];
}
}
}
public boolean checkWords (String str1, String str2) {
int difCount = 0;
for(int index = 0 , size = str1.length() ; index < size ; ++index) {
if(str1.charAt(index) != str2.charAt(index)) {
++difCount;
}
if(difCount > 1) {
return false;
}
}
if(difCount == 1){
return true;
}
else {
return false;
}
}
}
우선 백트래킹의 방식을 사용하여 솔루션을 작성했다.
boolean배열 visited를 통해 방문 여부를 판단하였으며,
모든 경로를 탐색해 가장 짧은 횟수를 저장하도록 설정하였다.
무한 루프를 방지하기 위해 최대 횟수 + 1 이상일 경우 다른 경로를 찾도록 설정했다.
solution의 작동 순서
- Main 클래스의 필드 int count 선언
- count를 최대 횟수 + 1로 설정
- backTracking 함수 실행
- 매개 변수 : words배열, 시작 단어, 타깃 단어, 진행 횟수, 방문 여부를 위한 boolean 배열
- 만약 count가 words배열의 길이와 다른 경우를 체크
words배열 내 타깃 단어의 존재 여부 판단 있을 경우 answer은 count, 아닌 경우 answer = 0
- answer를 반환
backTracking의 작동 순서
가장 짧은 경로를 찾음.
- 타깃 단어와 현재 단어가 동일한지 판단
- 동일한 경우 count와 tempCount 중 작은 값을 count에 저장
- 아닌 경우, tempCount 가 count보다 큰 경우를 판단 (무한 루프 및 불필요한 연산 제거)
- words 배열의 길이만큼 반복하는 for문 선언
- 방문하지 않고, checkWords의 결과가 true인 경우
- visited [index] 원소 값 반전
- 재귀 호출
매개 변수
- String [] words = words
- String now = words [index]
- String target = target
- int tempCount = tempCount + 1
- boolean [] visited = visited
checkWords의 작동 순서
두 단어의 알파벳 차이가 1개인지를 판단.
- 다른 알파벳의 개수를 판단하기 위한 int difCount = 0 선언
- String의 길이만큼 반복하는 for문 선언
- str1과 str2의 각 위치의 알파벳이 다르면 ++difCount
- difCount가 1을 초과하면 false를 반환
- for문에서 걸리지 않았고, 0이 아닌 경우 true를 반환
테스트 코드
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
class Programmers_DFS_BFS_3Test {
static Programmers_DFS_BFS_3 pdb3 = new Programmers_DFS_BFS_3();
@Test
void solution() {
String begin = "hit";
String target = "cog";
String[] words = {"hot","dot","dog","lot","log","cog"};
assertThat(4, is(pdb3.solution(begin, target, words)));
String[] words_2 = {"hot","dot","dog","lot","log"};
assertThat(0, is(pdb3.solution(begin, target, words_2)));
}
@Test
void testBackTracking() {
}
@Test
void testCheckWords() {
String str1 = "hit";
String str2 = "cog";
assertNotEquals(true, pdb3.checkWords(str1, str2));
str1 = "hit";
str2 = "hot";
assertThat(true, is(pdb3.checkWords(str1, str2)));
}
}