-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBFS.js
More file actions
executable file
·53 lines (48 loc) · 1.56 KB
/
BFS.js
File metadata and controls
executable file
·53 lines (48 loc) · 1.56 KB
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
/**
Breath first search
start="hit"
end="cog"
dict=["hot","dot","dog","lot","log"]
*/
// First override the String prototype to create the replaceAt function, since
// strings are immutable and cannot replace letters
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
// Define a "struct" for word nodes
var wordNode=function wordNode(word, numSteps) {
this.word=word;
this.numSteps=numSteps;
};
// Solution function
var bfsSolution=function bfsSolution(beginWord, endWord, wordDict) {
var queue=[];
queue.push(new wordNode(beginWord, 1));
wordDict.push(endWord);
while(queue.length!==0) {
var top=queue.shift(1);
var word=top.word;
if (word===endWord) {
return top.numSteps;
}
for (var i=0; i<word.length; i++) {
// letter codes from 'a' to 'z'
for (var c=97; c<=122; c++) {
var temp=word[i];
var letter=String.fromCharCode(c);
if (word[i]!==letter) {
word=word.replaceAt(i, letter);
}
var newWord=word;
var index=wordDict.indexOf(newWord);
if (index!==-1) {
queue.push(new wordNode(newWord, top.numSteps+1));
wordDict.splice(index,1);
}
word=word.replaceAt(i, temp);
}
}
}
return 0;
};
console.log(bfsSolution("hit", "cog", ["hot","dot","dog","lot","log"]));