您的位置:首页 > 其它

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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: