word ladder

来源:互联网 发布:苹果app加密软件 编辑:程序博客网 时间:2024/05/15 10:39
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence fromstart to end, 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.

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(start.compare(end) == 0)            return 0;//int count = 0;unordered_map<int, string> mp;unordered_map<string, int> inverse;unordered_set<string> vis;queue<string> q;int count = 1;int deep = 1;int len = start.length();q.push(start);while(count > 0){while(count > 0){string temp = q.front();if(temp.compare(end) == 0)return deep;q.pop();for(int i = 0; i < len; i++){char x = temp[i];for(char c = 'a'; c <= 'z'; c++){temp[i] = c;if(dict.count(temp) && !vis.count(temp)){vis.insert(temp);q.push(temp);}}temp[i] = x;}count--;}count = q.size();deep ++;}return 0;    }};


原创粉丝点击