leetcode word ladder 2 问题请教

wandouprincess 2013-04-12 01:25:04
大家好。我最近做到leetcode的一个问题怎么都解决不了。请教各位了!题目:
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]


我实现的方法是用queue ,set 和map来BFS。min代表是否找到最小路径的。
可是每次总有一个报错。
请各位高手帮忙看看!!不胜感谢!
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_set<string> visited;
queue<string> que;
visited.insert(start);
que.push(start);
vector<vector<string>> result;
map<string, string> backtrackmap;
backtrackmap[start]="";


int curlevel=1;
int curnum=1;
int nextnum=0;
bool min=false;

while(!que.empty())
{
string cur=que.front();
que.pop();
curnum--;
for(int i=0;i<cur.size();i++)
{
string temp=cur;
for(char c='a';c<='z';c++)
{
if(temp[i]!=c)
{
temp[i]=c;
if(dict.find(temp)!=dict.end() && visited.find(temp)==visited.end())
{
if(temp==end)
{
if(!min)
{
min=!min;
}
vector<string> list;
list.push_back(temp);
string temp1=cur;
while(!temp1.empty())
{
list.push_back(temp1);
temp1=backtrackmap[temp1];
}

reverse(list.begin(),list.end());
result.push_back(list);

}
else
{
que.push(temp);
visited.insert(temp);
backtrackmap[temp]=cur;
nextnum++;
}
}
}
}
}




if(curnum==0)
{
if(min) return result;
curnum=nextnum;
nextnum=0;
curlevel++;
}

}

return result;

}
};
...全文
98 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧