标签:
https://leetcode.com/problems/word-ladder/
http://www.lintcode.com/zh-cn/problem/word-ladder/
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
- 每次只能改变一个字母。
- 变换过程中的中间单词必须在字典中出现。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5
注意
- 如果没有转换序列则返回0。
- 所有单词具有相同的长度。
- 所有单词都只包含小写字母。
// --------------------------- // BFS non-recursive method // --------------------------- // // Using BFS instead of DFS is becasue the solution need the shortest transformation path. // // So, we can change every char in the word one by one, until find all possible transformation. // // Keep this iteration, we will find the shorest path. // // For example: // // start = "hit" // end = "cog" // dict = ["hot","dot","dog","lot","log","dit","hig", "dig"] // // +-----+ // +-------------+ hit +--------------+ // | +--+--+ | // | | | // +--v--+ +--v--+ +--v--+ // | dit | +-----+ hot +---+ | hig | // +--+--+ | +-----+ | +--+--+ // | | | | // | +--v--+ +--v--+ +--v--+ // +----> dot | | lot | | dig | // +--+--+ +--+--+ +--+--+ // | | | // +--v--+ +--v--+ | // +----> dog | | log | | // | +--+--+ +--+--+ | // | | | | // | | +--v--+ | | // | +--->| cog |<-- + | // | +-----+ | // | | // | | // +----------------------------------+ // // 1) queue <== "hit" // 2) queue <== "dit", "hot", "hig" // 3) queue <== "dot", "lot", "dig" // 4) queue <== "dog", "log" // class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { unordered_map<string, int> dis; dis.insert(make_pair(beginWord, 1)); queue<string> q; q.push(beginWord); while (!q.empty()) { string word = q.front(); q.pop(); if (word == endWord) { break; } for (int i = 0; i < word.size(); i++) { string tmp = word; for (char c = ‘a‘; c <= ‘z‘; c++) { tmp[i] = c; if (wordDict.count(tmp) == 1 && dis.count(tmp) == 0) { q.push(tmp); dis.insert(make_pair(tmp, dis[word] + 1)); } } } } if (dis.count(endWord) == 0) { return 0; } else { return dis[endWord]; } } };
标签:
原文地址:http://www.cnblogs.com/jianxinzhou/p/4515287.html