I was solving Word Ladder and I tried to use dfs instead of bfs but it's giving the wrong result and in editorial, it's said that dfs won't work. But I can't understand why. Please can someone explain and point out the mistake in my code.
class Solution {
HashMap<String,Integer> map ;
HashSet<String> visited;
int MAX = 10000;
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
map = new HashMap<>();
visited = new HashSet<>();
HashSet<String> set = new HashSet<>(wordList);
int ans = dfs(beginWord,endWord,set);
if(ans >= MAX) ans = 0;
return ans;
}
private int dfs(String word,String end,HashSet<String> wordSet){
if(word.equals(end)) return 1;
if(map.containsKey(word)) return map.get(word);
int min = MAX;
visited.add(word);
for(int i=0;i<word.length();i++){
for(char c='a';c<='z';c++){
String next = word.substring(0,i) + c + ((i!= word.length()-1)?word.substring(i+1):"");
if(!visited.contains(next)) {
if(wordSet.contains(next)){
min = Math.min(min,dfs(next,end,wordSet) + 1);
}
}
}
}
visited.remove(word);
map.put(word,min);
return min;
}
}
DFS can find shortest path but not always.
Suppose your graph has 4 nodes and 4 edges, edges are like this.
1 4
1 3
2 4
2 3
Here cycle exists.
So as we can see length of shortest path from 1 to 3 is 1 but we don't know how recursion will work in dfs.
If you start dfs from 1 it can go to 1 -> 4 -> 2 -> 3. In this path length from 1 to 3 will be 3 but it must be 1.
Graph which does not contain cycles(trees e.g.) dfs will find shortest path.