forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_170.js
65 lines (59 loc) Β· 1.61 KB
/
problem_170.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Find the shortest transformation sequence between 2 words
* @param {string[]} dict
* @param {string} word1
* @param {string} word2
* @return {string[]}
*/
function shortestSeq(beginWord, endWord, wordList) {
// base case
if (beginWord.length !== endWord.length) return null;
const seen = {};
const queue = [beginWord];
const final = [];
while (queue.length) {
// for every word in queue
for (let i = 0; i < queue.length; i++) {
const curr = queue.shift();
// for every word in wordlist
for (let j = 0; j < wordList.length; j++) {
const word = wordList[j];
// check if current word in queue is adjacent to word in word list
if (isAdjacent(curr, word)) {
// check if word in wordlist is endword
if (word === endWord) {
// add begining and start word
final.unshift(beginWord);
final.push(endWord);
return final;
}
// mark words if you've seen them
if (!seen[word]) {
seen[word] = true;
queue.push(word);
final.push(word);
}
}
}
}
}
return [];
}
/**
* Checks if words are adjacent to one another (1 away)
* @param {string} w1
* @param {string} w2
* @return {boolean}
*/
function isAdjacent(w1, w2) {
let count = 0;
for (let i = 0; i < w1.length; i++) {
if (w1[i] !== w2[i]) count++;
if (count > 1) break;
}
return count === 1;
}
const wordList = ['dot', 'dop', 'dat', 'cat'];
const beginWord = 'dog';
const endWord = 'cat';
console.log(shortestSeq(beginWord, endWord, wordList));