forked from laviii123/Btecky
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
laviii123#242 This code uses BFS to find the length of the shortest transformation sequence from beginWord to endWord in the given wordList. It returns the length of the sequence or 0 if no such sequence exists.
- Loading branch information
1 parent
0598911
commit de112f8
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
//#242 java code | ||
import java.util.*; | ||
|
||
public class WordLadderI { | ||
public int ladderLength(String beginWord, String endWord, List<String> wordList) { | ||
Set<String> dict = new HashSet<>(wordList); | ||
if (!dict.contains(endWord)) { | ||
return 0; | ||
} | ||
|
||
Queue<String> queue = new LinkedList<>(); | ||
queue.offer(beginWord); | ||
int level = 1; | ||
|
||
while (!queue.isEmpty()) { | ||
int size = queue.size(); | ||
|
||
for (int i = 0; i < size; i++) { | ||
String word = queue.poll().toLowerCase().trim().replaceAll("[^a-zA-Z]", ""); | ||
if (word.equals(endWord)) { | ||
return level; | ||
} | ||
|
||
char[] chars = word.toCharArray(); | ||
for (int j = 0; j < word.length(); j++) { | ||
char originalChar = chars[j]; | ||
|
||
for (char c = 'a'; c <= 'z'; c++) { | ||
if (c == originalChar) continue; | ||
chars[j] = c; | ||
String newWord = new String(chars); | ||
|
||
if (dict.contains(newWord)) { | ||
queue.offer(newWord); | ||
dict.remove(newWord); | ||
} | ||
} | ||
chars[j] = originalChar; | ||
} | ||
} | ||
|
||
level++; | ||
} | ||
|
||
return 0; | ||
} | ||
|
||
public static void main(String[] args) { | ||
String beginWord = "hit"; | ||
String endWord = "cog"; | ||
List<String> wordList = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"); | ||
|
||
WordLadderI wordLadderI = new WordLadderI(); | ||
int ladderLength = wordLadderI.ladderLength(beginWord, endWord, wordList); | ||
System.out.println("Shortest transformation sequence length: " + ladderLength); | ||
} | ||
} |