import java.util.*;
import java.lang.*;
class Solution {
ArrayList<List<String>> answer = new ArrayList<>();
ArrayList<List<String>> realAnswer = new ArrayList<>();
List<String> wordList;
int lowSize = Integer.MAX_VALUE;
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
this.wordList = wordList;
dfs(beginWord,endWord,new ArrayList<String>());
for(List<String> temp : answer)
if(temp.size()==lowSize) realAnswer.add(temp);
return realAnswer;
}
public void dfs(String beginWord, String endWord,ArrayList<String> list){
list.add(beginWord);
if(beginWord.equals(endWord)){
answer.add(list);
lowSize = Math.min(lowSize,list.size());
return;
}
for(String word : wordList){
if(!list.contains(word)&&getEditDistance(beginWord,word)==1){
ArrayList<String> clone = new ArrayList(list);
dfs(word,endWord,clone);
}
}
}
public int getEditDistance(String s1,String s2){
int[][] distance = new int[s1.length()+1][s2.length()+1];
for(int i=0; i<=s1.length(); i++){
distance[i][0] = i;
distance[0][i] = i;
}
for(int i=0; i<s1.length(); i++){
for(int j=0; j<s2.length(); j++){
if(i==j){
if(s1.charAt(i)==s2.charAt(j))
distance[i+1][j+1] = distance[i][j];
else
distance[i+1][j+1] = distance[i][j] + 1;
}else{
distance[i+1][j+1] = Math.min(distance[i][j+1],distance[i+1][j])+1;
}
}
}
return distance[s1.length()][s2.length()];
}
}
포스팅용 소스코드 저장 용 (시간 초과 코드)