Does dfs does not guarantee shortest path in a graph

Revision en1, by Tanmay, 2021-01-10 11:48:32

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;
    }
}
Tags #dfs and similar, #graph, #shortest_path

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Tanmay 2021-01-10 11:48:32 1528 Initial revision (published)