您的位置:首页 > 编程语言 > C语言/C++

127.Word Ladder

2016-03-31 11:07 423 查看
昨天晚上在LeetCode随便选了一道题写会儿代码,选中了Word Ladder,这道题刚开始只是有一点思路,不知道具体往下怎么做,先看看题吗要求如下:

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list

For example,

Given:
beginWord = 
"hit"

endWord = 
"cog"

wordList = 
["hot","dot","dog","lot","log"]


As one shortest transformation is 
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
,

return its length 
5
.

Note:

Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
刚开始看到这道题时想了一会儿,第一想法是创建一个二维数组,数组中的横行和纵行分别对应所有的单词,将横行和纵行中长度相同并且只有一位不同的两个单词对应的位置设置为1,其他情况下设置为0.接着,看到二维数组想到图中的邻接矩阵,想到可以用图轮方面的知识解答该题,但是具体用什么方法没有思路。于是,上网查了一下,才知道可以使用广度优先搜索来做,一下子想起来在《数据结构与算法分析:C语言描述》中,在关于图的那一章中讲到单点最短路径的时候,曾经讲过在边没有权值的时候,可以使用广度优先遍历来求解最短路径问题。
代码如下:

#include<iostream>
#include<string>
#include<queue>
#include<unordered_set>
#include<map>

using namespace std;

class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
queue<string> que;
map<string, int> map;

if( beginWord == "" || endWord == "" || wordList.empty() )
return 0;
if( beginWord == endWord )
return 1;
que.push( beginWord );
map.insert( pair<string, int>( beginWord, 1) );

while( !que.empty() )
{
string currentWord = que.front();
que.pop();
int currentLength = map[ currentWord ];
for( int index = 0; index < currentWord.length(); index++ )
{
for( char ch = 'a'; ch <= 'z'; ch++ )
{
string temp = currentWord;
//判断是否重复
if( ch == temp[ index ])
continue;
temp[ index ] = ch;
if( temp == endWord )
return currentLength+1;
//判断是否重复
if( !map.count( temp ) && wordList.count( temp ) )
{
que.push( temp );
map.insert(pair<string, int>(temp, currentLength+1) );
}
}
}
}
return 0;
}
};

由于该程序中使用了unordered_set类,所以编译的时候采用如下命令进行:

g++ -std=c++11 -o q127 q127.cp


这是我第二次提交的程序,在第一次提交的程序中,由于在加入到map中和修改字母的时候没有判断重复而超时运行,所以在书写广度优先搜索的时候判断是否重复是非常重要的。
有关广度优先遍历的详细总结可以看此链接:http://www.acmerblog.com/leetcode-bfs-6431.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  广度优先搜索 C++