昨天晚上在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.
代码如下:
#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
有关广度优先遍历的详细总结可以看此链接:http://www.acmerblog.com/leetcode-bfs-6431.html