Online Judge Solutions

Thursday, December 25, 2014

Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary
Note
  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
 
int ladderLength(string start, string end, unordered_set<string> &dict) {
        int rounds = 1;
        queue<string> que;
        que.push(start);
        
        while(que.size() > 0)
        {
            int qSize = que.size();
            while(--qSize >=0) {
              string w = que.front();
              que.pop();
            
              if (w == end) return rounds;
            
              for (int i = 0; i < w.length(); i++) {
                char c = w[i];
                for(int j= 'a'; j <= 'z'; j++) {
                    w[i] = j;
                    if (j != c && dict.count(w) == 1) {
                       que.push(w);
                       dict.erase(w);
                    }
                }
                w[i] = c;
              }
            }
            rounds++;
        }
        
        return 0;
    }

2 comments:

  1. if (w == end) return rounds; for this line, I think it may has problem what if the end string is not in part of dictionary.

    ReplyDelete
  2. right, we probably should assert both start and end exist in the dict at the beginning

    ReplyDelete