A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> … -> sk such that:
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output: 5
Explanation: One shortest transformation sequence is “hit” -> “hot” -> “dot” -> “dog” -> cog", which is 5 words long.
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
Output: 0
Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.
From: LeetCode
Link: 127. Word Ladder
bool isOneLetterDiff(char *a, char *b) {
int diffCount = 0;
while (*a) {
if (*(a++) != *(b++)) diffCount++;
if (diffCount > 1) return false;
}
return diffCount == 1;
}
int ladderLength(char *beginWord, char *endWord, char **wordList, int wordListSize) {
if (!beginWord || !endWord || !wordList || wordListSize == 0) return 0;
bool *visited = (bool *)calloc(wordListSize, sizeof(bool));
char **queue = (char **)malloc(sizeof(char *) * (wordListSize + 1));
int front = 0, rear = 0;
queue[rear++] = beginWord;
int level = 1;
while (front < rear) {
int size = rear - front;
for (int i = 0; i < size; i++) {
char *word = queue[front++];
if (strcmp(word, endWord) == 0) {
free(visited);
free(queue);
return level;
}
for (int j = 0; j < wordListSize; j++) {
if (!visited[j] && isOneLetterDiff(word, wordList[j])) {
visited[j] = true;
queue[rear++] = wordList[j];
}
}
}
level++;
}
free(visited);
free(queue);
return 0;
}