AlgoDaily Solution
1var assert = require('assert');
2
3function wordLadder(begin, end, wordList) {
4 let len = 1;
5 let queue = [begin];
6 const dict = new Set(wordList);
7 const seen = new Set(queue);
8
9 while (queue.length) {
10 const next = [];
11 for (let node of queue) {
12 if (node === end) {
13 return len;
14 }
15
16 const splitNode = node.split('');
17 for (let i = 0; i < splitNode.length; i++) {
18 for (let d = 0; d < 26; d++) {
19 splitNode[i] = String.fromCharCode(97 + d);
20 const nv = splitNode.join('');
21 if (!seen.has(nv) && dict.has(nv)) {
22 next.push(nv);
23 seen.add(nv);
24 }
25 splitNode[i] = node[i];
26 }
27 }
28 }
29 queue = next;
30 len++;
31 }
32
33 return 0;
34}
35
36try {
37 assert.equal(
38 wordLadder('bold', 'hope', [
39 'hope',
40 'hole',
41 'bold',
42 'hold',
43 'cold',
44 'sold',
45 'dold',
46 ]),
47 4
48 );
49
50 console.log(
51 'PASSED: ' +
52 "`wordLadder('bold', 'hope', ['hope', 'hole', 'bold', 'hold', 'cold', 'sold', 'dold'])` should return `4`"
53 );
54} catch (err) {
55 console.log(err);
56}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
28
var assert = require('assert');
function wordLadder(begin, end, wordList) {
// fill this in
}
try {
assert.equal(
wordLadder('bold', 'hope', [
'hope',
'hole',
'bold',
'hold',
'cold',
'sold',
'dold',
]),
4
);
console.log(
'PASSED: ' +
"`wordLadder('bold', 'hope', ['hope', 'hole', 'bold', 'hold', 'cold', 'sold', 'dold'])` should return `4`"
);
} catch (err) {
console.log(err);
}
OUTPUT
Results will appear here.