문제링크 : https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수
programmers.co.kr
class Solution {
public static boolean visited[] = new boolean[51];
//s1에서 한 문자만 바꿔서 s2가 가능한지
public static boolean availTrans(String s1, String s2){
int cnt = 0;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)!=s2.charAt(i))cnt++;
}
if(cnt==1)return true;
return false;
}
public static int dfs(String begin, String target, String[] words){
if(begin.equals(target)){
return 0;
}
System.out.println("현재 단어 : " + begin);
int answer = 987654321;
for(int i=0;i<words.length;i++){
if(visited[i]) continue;
if(!availTrans(begin,words[i])) continue;
visited[i] = true;
answer = Math.min(answer,dfs(words[i],target,words)+1);
visited[i] = false;
}
return answer;
}
public static int solution(String begin, String target, String[] words) {
int answer = dfs(begin,target,words);
if(answer==987654321){
return 0;
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 징검다리 건너기 / JAVA (0) | 2022.02.18 |
---|---|
[프로그래머스] 여행경로 / JAVA (0) | 2022.02.18 |
[프로그래머스] 등굣길 / JAVA (0) | 2022.02.18 |
[프로그래머스] 2 X N 타일링 / JAVA (0) | 2022.02.18 |
[프로그래머스] GPS / JAVA (1) | 2022.02.18 |