您的位置:首页 > 其它

word ladder

2016-06-29 15:13 316 查看
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) fromstart 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"]
]


Note:

All words have the same length.

All words contain only lowercase alphabetic characters.

思路参照路径查找,递归查找dict中和start相邻的下一个元素,但是不知道为什么在vs上运行的结果和网上提交的运行的不同

class Solution {
public:
bool isnext(string s1, string s2)//判断两个字符串是否是只有一个字母不同
{
int count = 0;

for (int i = 0, j = 0; i<s1.size(), j<s2.size(); i++, j++)
{
  if (s1[i] != s2[j])
    count++;
}
if (count == 1)
  return true;
else
  return false;
}
void findpath(string start, string end, unordered_set<string> &dict, vector<string>&path,   vector<vector<string>>&res)
  {
  path.push_back(start);
  if (isnext(start, end))//到最后一个了
  {
    path.push_back(end);
    res.push_back(path);
    path.pop_back();
  }

  unordered_set<string>::iterator it;
  if (dict.find(start) == dict.end())//这如果不讨论的话会导致递归进入死循环
    it = dict.begin();
  else
  {
    it = dict.find(start);

  }

for (; it != dict.end(); it++)
{
  if (isnext(start, *it))
{

unordered_set<string> ndict (it, dict.end());
findpath(*it, end, ndict, path, res);

path.pop_back();
}
}
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
  vector<string>path;
  vector<vector<string>>res;
  findpath(start, end, dict, path, res);
  return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: