Word Ladder

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For 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.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

struct Node
{
	string val;
	int distance;
	Node(string a, int b) : val(a), distance(b)
	{}
};

class Solution {
public:
    bool oneDistance(const string &a, const string &b)
    {
	    int result = 0;
	    int len = a.length();
	    for (int i = 0; i < len; i++)
	    {
		    if (a[i] != b[i])
		    {
			    result++;
		    }
	    }

	    return result == 1;
    }

    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        if (oneDistance(beginWord, endWord))
        {
            return 2;
        }
        set<string> dict;
        for (unordered_set<string>::iterator it = wordDict.begin(); it != wordDict.end(); it++)
        {
            dict.insert(*it);
        }
        dict.erase(beginWord);
        dict.erase(endWord);
        
	    queue<Node> visited;
	    visited.push(Node(beginWord, 1));

	    while (!visited.empty())
	    {
		    Node front = visited.front();
		    for (set<string>::iterator it = dict.begin(); it != dict.end(); it++)
		    {
			    if (oneDistance(front.val, *it))
			    {
				    if (oneDistance(*it, endWord))
				    {
					    return front.distance+2;
				    }
				    else
				    {
					    visited.push(Node(*it, front.distance+1));
					    dict.erase(*it);
				    }
			    }
		    }

		    visited.pop();
	    }

	    return 0;
    }
};


你可能感兴趣的:(Word Ladder)