Given two words A and B, and a dictionary, C, find the length of shortest transformation sequence from A to B, such that:
You must change exactly one character in every transformation.
Each intermediate word must exist in the dictionary.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
Input Format:
The first argument of input contains a string, A.
The second argument of input contains a string, B.
The third argument of input contains an array of strings, C.
Output Format:
Return an integer representing the minimum number of steps required to change string A to string B.
Input 1:
A = "hit"
B = "cog"
C = ["hot", "dot", "dog", "lot", "log"]
Output 1:
5
Explanation 1:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
Solution:
public class Solution {
static class Word {
String str;
public Word(String s) {
this.str = s;
}
@Override
public int hashCode() {
return str.hashCode();
}
@Override
public boolean equals(Object o) {
Word w = (Word) o;
return str.equals(w.str);
}
public boolean valid(Set<String> set, Word w) {
return set.contains(str) && diff(w) == 1;
}
public int diff(Word w) {
int d = 0;
for (int i = 0; i < str.length(); i ++) {
if (str.charAt(i) != w.str.charAt(i)) {
d ++;
}
}
return d;
}
}
public int solve(String A, String B, ArrayList<String> C) {
Word start = new Word(A);
Word end = new Word(B);
Deque<Word> queue = new ArrayDeque<>();
Set<String> set = new HashSet<>(C);
Set<Word> visited = new HashSet<>();
queue.offer(start);
int step = 0;
while (!queue.isEmpty()) {
step ++;
int size = queue.size();
for (int i = 0; i < size; i ++) {
Word curr = queue.poll();
if (curr.equals(end)) {
return step;
}
if (visited.add(curr)) {
for (String s : C) {
Word next = new Word(s);
if (next.valid(set, curr)) {
queue.offer(next);
}
}
}
}
}
return 0;
}
}
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> set = new HashSet(wordList);
Deque<String> queue = new ArrayDeque();
Set<String> visited = new HashSet();
queue.offer(beginWord);
visited.add(beginWord);
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
step ++;
for (int j = 0; j < size; j ++) {
String curr = queue.poll();
if (curr.equals(endWord)) {
return step;
}
char[] arr = curr.toCharArray();
for (int i = 0; i < arr.length; i ++) {
char c = arr[i];
for (char k = 'a'; k <= 'z'; k ++) {
arr[i] = k;
String next = new String(arr);
if (set.contains(next) && visited.add(next)) {
queue.offer(next);
}
}
arr[i] = c;
}
}
}
return 0;
}
}