From 020d2ebb4de171ab65678a44be57f169ccea7209 Mon Sep 17 00:00:00 2001 From: Devansh Chandak <51949082+dchandak99@users.noreply.github.com> Date: Sun, 5 Apr 2020 12:34:47 +0530 Subject: [PATCH] Update WordLadder-I.cpp Reduced running time with preprocessing --- Graphs/WordLadder-I.cpp | 76 ++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/Graphs/WordLadder-I.cpp b/Graphs/WordLadder-I.cpp index b698b6f..0919518 100644 --- a/Graphs/WordLadder-I.cpp +++ b/Graphs/WordLadder-I.cpp @@ -1,34 +1,48 @@ -struct e{ - string w; // word - int d; //distance - e(string _w, int _d): w(_w), d(_d) {} -}; +int Solution::solve(string beginWord, string endWord, vector& wordList) { + int n=beginWord.size(); + unordered_map > dict; + string word; + + for(int i=0;i visited; + queue > q; -bool neighbor(const string &q, const string &p){ - int diff=0, size=q.size(); - for(int i=0 ; i &dictV) { - unordered_map mark; - queue Q; - - Q.push(e{start, 1}); mark[start] = 1; - while(Q.size()){ - e fro = Q.front(); Q.pop(); //<<--- notice - if(fro.w == end) return fro.d; + q.push(make_pair(beginWord, 1)); + visited.insert(beginWord); + + while(!q.empty()) + { + pair x = q.front(); + q.pop(); + string word = x.first; + + for(int i=0;i::iterator it = dict[adj].begin();it!=dict[adj].end();++it) + { string adj_word=*it; + if(adj_word==endWord) + return x.second+1; + if(visited.find(adj_word)==visited.end()) + { + visited.insert(adj_word); + q.push(make_pair(adj_word,x.second+1)); + } + } + + } + - for(const string &word : dictV){ - if(neighbor(fro.w, word) and !mark[word]){ - Q.push(e{word, fro.d + 1}); - mark[word]=1; - } } - } - return 0; -} \ No newline at end of file + return 0; + + } + +