http://oj.leetcode.com/problems/word-ladder/

图的最短路径问题,可以用最短路径算法,也可以深搜,也可以广搜。

深搜版本:

第一次写的时候,把sum和visited都自然的设置成了传引用,导致递归调用下去之后,再返回来,反而各种参数的值退不回来了。然后把sum和visited改成了传值,这样反而适应了本程序意图。可见,也不是什么时候都需要传引用的。具体在写程序的时候,需要传值还是传引用,要具体分析。传引用和传值的情况分别如下:

void DFS(string currentWord,string endWord,int &sum, unordered_set<string> &dict,map<string,bool>  &visited,int  &minDistance)
void DFS(string currentWord,string endWord,int &sum, unordered_set<string> &dict,map<string,bool>  &visited,int  &minDistance)
另外,还遇到了一个问题,在递归调用层次下去又上来后,对本层循环的,后续影响。所以又添加了两个变量,int tempSum;和map<string,bool> tempVisited;。给它们赋值成参数刚进来的样子,这样就摒除了同层循环间的相互影响。

深搜版本超时了,继续改……
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <map>
#include <hash_map>
#include <limits.h>
using namespace std; class Solution {
public: int calcDistance(string a,string b)
{
int sum = ;
for(int i = ;i<a.size();i++)
{
if(a[i]!=b[i])
sum++;
}
return sum;
} void DFS(string currentWord,string endWord,int sum, unordered_set<string> &dict,map<string,bool> visited,int &minDistance)
{
if(calcDistance(currentWord,endWord)==)
{
sum++;
if(minDistance> sum)
minDistance = sum;
return;
}
int tempSum;
map<string,bool> tempVisited;
for(unordered_set<string>::iterator iter = dict.begin();iter!=dict.end();iter++)
{
if(visited[*iter]==false && calcDistance(currentWord,*iter)==)
{
visited[*iter] = true;
tempSum = sum;
tempSum++;
tempVisited = visited;
DFS(*iter,endWord,tempSum,dict,visited,minDistance);
}
}
} int ladderLength(string start, string end, unordered_set<string> &dict) { string currentWord = start; int sum = ; map<string,bool> visited; for(unordered_set<string>::iterator iter = dict.begin();iter!=dict.end();iter++)
visited[*iter] = false; int minDistance = INT_MAX; DFS(currentWord,end,sum,dict,visited,minDistance); return minDistance;
}
}; int main()
{
Solution *mySolution = new Solution(); unordered_set<string> dict;
dict.insert("hot");
dict.insert("dot");
dict.insert("dog");
dict.insert("lot");
dict.insert("log");
string start = "hit";
string end = "cog"; cout<<mySolution->ladderLength(start,end,dict);
return ;
}

然后,写了一个广搜版本的,代码如下:

class Solution {

public:
class node{
public:
int distance;
string word;
bool visited;
public:
node()
{
distance = ;
word.clear();
visited = false;
}
}; int testDistance(string test,string end)
{
int distance = ;
for(int i = ;i<test.size();i++)
if(test[i]!= end[i])
distance++;
return distance;
} int ladderLength(string start, string end, unordered_set<string> &dict) { vector<node*> wordVector; unordered_set<string>::iterator itor=dict.begin(); for(int i = ;i<dict.size();i++)
{
node *myNode = new node();
myNode->word = *itor;
itor++;
wordVector.push_back(myNode);
} node *myNode = new node();
myNode->word = start; queue<node*> wordQueue;
wordQueue.push(myNode); node *topNode= new node(); while(!wordQueue.empty())
{
topNode = wordQueue.front();
wordQueue.pop();
if(testDistance(topNode->word,end) == )
{
return topNode->distance+;
}
else
{
node *pIndexNode = new node();
for(vector<node*>::iterator itor = wordVector.begin();itor!=wordVector.end();itor++)
{
pIndexNode = *itor;
if(pIndexNode->visited == false && testDistance(pIndexNode->word,topNode->word)==)
{
pIndexNode->visited = true;
pIndexNode->distance = topNode->distance+;
wordQueue.push(pIndexNode);
}
}
}
} }
};

在这个过程中,刚开始写的是

return topNode->distance++;就直接这样返回了,写程序过程中,细心不够,这样返回是distance本来的值,然后distance会++,但是那也没用了。

仍然没过。但是相比之下,广搜比深搜,在测试数据上有进步了。继续改进广搜版本,将testDistance函数改了,并且还是用了eraser函数,将已经加入过的元素删除了,代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <queue>
using namespace std; class Solution {
public:
class node{
public:
int distance;
string word;
public:
node()
{
distance = ;
word.clear();
}
}; bool testDistance(string test,string end)
{
int distance = ;
for(int i = ;i<test.size();i++)
{
if(test[i]!= end[i])
distance++;
if(distance>=)
return false;
}
return true;
} int ladderLength(string start, string end, unordered_set<string> &dict) { vector<node*> wordVector; unordered_set<string>::iterator itor=dict.begin(); for(int i = ;i<dict.size();i++)
{
node *myNode = new node();
myNode->word = *itor;
itor++;
wordVector.push_back(myNode);
} node *myNode = new node();
myNode->word = start; queue<node*> wordQueue;
wordQueue.push(myNode); node *topNode= new node(); while(!wordQueue.empty())
{
topNode = wordQueue.front();
wordQueue.pop();
if(testDistance(topNode->word,end))
{
return topNode->distance+;
}
else
{
node *pIndexNode = new node();
for(vector<node*>::iterator itor = wordVector.begin();itor!=wordVector.end();)
{
pIndexNode = *itor;
if(testDistance(pIndexNode->word,topNode->word))
{
pIndexNode->distance = topNode->distance+;
wordQueue.push(pIndexNode);
itor = wordVector.erase(itor);
}
else
itor++;
}
}
} }
}; int main()
{
Solution *mySolution = new Solution(); unordered_set<string> dict;
dict.insert("hot");
dict.insert("dot");
dict.insert("dog");
dict.insert("lot");
dict.insert("log");
string start = "hit";
string end = "cog"; cout<<mySolution->ladderLength(start,end,dict);
return ;
}

虽然每一步都有学习到新东西,也学会了些深搜和广搜,但是这道题目仍然超时,现在考虑用空间换时间。

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <queue>
using namespace std; class Solution {
public:
bool testDistance(string test,string end)
{
int distance = ;
for(int i = ;i<test.size();i++)
{
if(test[i]!= end[i])
distance++;
if(distance>=)
return false;
}
return true;
} void BuildAdjacentList(string &word, unordered_map< string,unordered_set<string> >&adjacentList,const unordered_set<string> &dict)
{
string original = word;
for(size_t pos = ;pos<word.size();pos++)
{
char beforeChange = ' ';
for(int i = 'a';i<'z';++i)
{
beforeChange = word[pos];
if(beforeChange == i)
{
continue;
}
word[pos] = i;
if(dict.count(word)>)
{
auto iter = adjacentList.find(original);
if(iter!= adjacentList.end())
iter->second.insert(word);
else
{
adjacentList.insert(pair<string,unordered_set<string> >(original,unordered_set<string>()));
adjacentList[original].insert(word);
}
}
word[pos] = beforeChange;
}
}
} int ladderLength(string start, string end, unordered_set<string> &dict) { queue<pair<string,int> > wordQueue;
wordQueue.push(make_pair(start,)); unordered_map< string,unordered_set<string> > adjacentList; string topWord; int ans = ; unordered_set<string> visited;
visited.insert(start); while(!wordQueue.empty())
{
topWord = wordQueue.front().first; if(testDistance(topWord,end))
{
return wordQueue.front().second+;
}
else
{
BuildAdjacentList(topWord,adjacentList,dict); auto iter = adjacentList.find(topWord);
if(iter!= adjacentList.end())
{
for(unordered_set<string>::iterator iterset = iter->second.begin();iterset!= iter->second.end();iterset++)
{
if(visited.find(*iterset)==visited.end())
{
wordQueue.push(make_pair(*iterset,wordQueue.front().second+));
visited.insert(*iterset);
} }
} }
wordQueue.pop();
}
return ;
}
}; int main()
{
Solution *mySolution = new Solution(); unordered_set<string> dict;
dict.insert("hot");
//dict.insert("dot");
dict.insert("dog");
//dict.insert("lot");
//dict.insert("log");
string start = "hot";
string end = "dog"; cout<<mySolution->ladderLength(start,end,dict);
return ;
}

上面的这份代码,终于AC了,果然考察的重点在另一个思路上。其实,也用不着用空间来存储。比如可以使用更精简的代码,如下:

class Solution{
public:
int ladderLength(string start,string end,unordered_set<string> &dict)
{
queue<pair<string ,int > > wordQueue;
unordered_set<string> visited;
wordQueue.push(make_pair(start,));
visited.insert(start); while(!wordQueue.empty())
{
string curStr = wordQueue.front().first;
int curStep = wordQueue.front().second;
wordQueue.pop(); for(int i = ;i<curStr.size();i++)
{
string tmp = curStr;
for(int j = ;j<;++j)
{
tmp[i] = j+'a';
if(tmp == end)
return curStep+;
if(visited.find(tmp) == visited.end() && dict.find(tmp)!=dict.end())
{
wordQueue.push(make_pair(tmp,curStep+));
visited.insert(tmp);
}
}
}
}
return ; }
};

加油!

 其实,这道题的重点不在于深搜、广搜剪枝之类的。换个角度说的话,dict很大,多次遍历它的话,影响时间,然后换个思路……

LeetCode OJ——Word Ladder的更多相关文章

  1. Java for LeetCode 126 Word Ladder II 【HARD】

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  2. [LeetCode] 126. Word Ladder II 词语阶梯 II

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  3. [LeetCode] 127. Word Ladder 单词阶梯

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  4. LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...

  5. [Leetcode Week5]Word Ladder II

    Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...

  6. [Leetcode Week5]Word Ladder

    Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...

  7. [LeetCode] 126. Word Ladder II 词语阶梯之二

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  8. 【leetcode】Word Ladder

    Word Ladder Total Accepted: 24823 Total Submissions: 135014My Submissions Given two words (start and ...

  9. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

随机推荐

  1. 如何用 CSS 和 D3 创作一个无尽的六边形空间

    效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/NBvrWL 可交互视频 此视频是可 ...

  2. 多本Python极速入门最佳书籍,不可错过的Python学习资料!

    Python作为现在很热门的一门编程语言,介于Python的友好,许多的初学者都将其作为首选,为了帮助大家更好的学习Python,我筛选了2年内优秀的python书籍,个别经典的书籍扩展到5年内.   ...

  3. statistics-skewed data

    参考文献: http://www.statisticshowto.com/skewed-distribution/ left/negatively-skewed distributions : box ...

  4. Leetcode 145. 二叉树的后序遍历

    题目链接 https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/ 题目描述 给定一个二叉树,返回它的 ...

  5. CF 219 D:Choosing Capital for Treeland(树形dp)

    D. Choosing Capital for Treeland 链接:http://codeforces.com/problemset/problem/219/D   The country Tre ...

  6. action属性和data属性组合事例

  7. jdk生成证书,网站请求变成https

    生成证书的步骤 1.进入jdk的bin目录 keytool -genkey -alias tomcat -keyalg RSA   命名证书的名字叫tomcat 2.将证书拷贝至tomcat的bin目 ...

  8. 配置hibernate常见问题

    连接MySql时出现:The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time z ...

  9. 大数据学习——actor编程

    1 概念 Scala中的Actor能够实现并行编程的强大功能,它是基于事件模型的并发机制,Scala是运用消息(message)的发送.接收来实现多线程的.使用Scala能够更容易地实现多线程应用的开 ...

  10. 零基础自学用Python 3开发网络爬虫

    原文出处: Jecvay Notes (@Jecvay) 由于本学期好多神都选了Cisco网络课, 而我这等弱渣没选, 去蹭了一节发现讲的内容虽然我不懂但是还是无爱. 我想既然都本科就出来工作还是按照 ...