public class Solution {
public int LadderLength(string beginWord, string endWord, ISet<string> wordList)
{
if(beginWord.Length == 1 )
{
return beginWord[0] != endWord[0] ? 2 : 0;
}
wordList.Remove(beginWord);
wordList.Add(endWord);
var matchedWords = new HashSet<string>();
matchedWords.Add(beginWord);
var found = false;
var result = new List<ISet<string>>(){matchedWords};
while(matchedWords.Count > 0 && !found){
var nextRound = new HashSet<string>();
foreach(var w in matchedWords){
if(w == endWord){
found = true;
break;
}
else{
var r = NextLadderWords(w, ref wordList);
foreach(var w1 in r){
nextRound.Add(w1);
}
}
}
matchedWords = nextRound;
if(!found){
result.Add(nextRound);
}
}
return found ? result.Count : 0;
}
private ISet<string> NextLadderWords(string word,ref ISet<string> words){
var ret = new HashSet<string>();
var len = word.Length;
for(var i = 0;i < len; i++){
var c = (int)word[i];
for(var j = ‘a‘; j <= ‘z‘; j++){
if(c != j){
var newWord = word.ToCharArray();
newWord[i] = (char)j;
var s = new string(newWord);
if(words.Contains(s)){
ret.Add(s);
words.Remove(s);
}
}
}
}
return ret;
}
}原文:http://blog.csdn.net/lan_liang/article/details/50144399