LINTCODE——单词接龙
2017-09-22 20:20
281 查看
LINTCODE——单词接龙
思路:先设计一个无序图,然后宽度优先搜索遍历;
思路:先设计一个无序图,然后宽度优先搜索遍历;
class Solution { public: /** * @param start, a string * @param end, a string * @param dict, a set of string * @return an integer */ int ladderLength(string start, string end, unordered_set<string> &dict) { // write your code here if(check(start,end)) return 2; if(start == end) return 1; int n = dict.size(); vector<string> dicts(dict.begin(),dict.end()); //生成无向图,adj[i]里面存放的是能与dicts[i]直接转换的字符串下标 vector<vector<int> > adj; for(int i = 0 ; i < n ; i++) { vector<int> temp; for(int j = 0 ; j < n ;j++) { if(i != j && check(dicts[i],dicts[j])) temp.push_back(j); } adj.push_back(temp); temp.clear(); } queue<int> Q; for(int i = 0 ; i < n ;i++) if(check(start,dicts[i])) Q.push(i); //宽度优先搜索,定义一个bool数组,记录访问过的元素 vector<bool> record(n,false); int count = 1; while(!Q.empty()) { int length = Q.size(); while(length > 0) { int v = Q.front(); Q.pop(); for(auto x : adj[v]) { if(check(dicts[v],end)) return count+2; if(!record[x]) { record[x] = true; Q.push(x 4000 ); } } length--; } count++; } return 0; } bool check(string a,string b) { int flag = 0; for(int i = 0 ; i < a.size() ; i++) { if(a[i] != b[i]) { if(flag == 1) return false; else flag++; } } return (flag == 1) ? true : false; } };
相关文章推荐
- ***[Lintcode]Word Ladder 单词接龙
- 单词接龙 II-LintCode
- LintCode 120-单词接龙 广度优先搜索
- LintCode-单词接龙II
- lintcode,单词接龙
- LintCode_单词接龙
- 单词接龙-LintCode
- lintcode-120-单词接龙
- lintcode 单词接龙II
- 百度2017暑期实习生编程题:单词接龙
- LintCode:M-单词切分
- 中兴测试题目-单词字母接龙
- lintcode-单词接龙-120
- NOIP 2000 单词接龙
- Codevs P1018 单词接龙
- 单词接龙
- **[Lintcode]Word Break单词切分
- 图论欧拉路径问题(单词接龙)
- LintCode 133 最长单词
- lintcode ----最后一个单词长度