您的位置:首页 > 其它

Word Ladder

2013-10-20 14:47 399 查看
I:

BFS

class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int res=1, n1=1, n2=0;
queue<string> q;
unordered_set<string> use;
q.push(start);
while (q.size()) {
while (n1) {
string ss=q.front();
q.pop();
n1--;
for (int i=0; i<ss.size(); i++) {
for (int j='a'; j<='z'; j++) {
string s=ss;
s[i]=(char) j;
if (s==end) {
return res+1;
}
if (dict.find(s)!=dict.end() && use.find(s)==use.end()) {
q.push(s);
n2++;
use.insert(s);
}
}
}
}
n1=n2;
n2=0;
res++;
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: