-
Notifications
You must be signed in to change notification settings - Fork 1
/
127.Graph.M.word-ladder.js
41 lines (39 loc) · 1013 Bytes
/
127.Graph.M.word-ladder.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
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function (beginWord, endWord, wordList) {
if (!wordList.includes(endWord)) return 0
const visitedRecord = {}
let result = 1
wordList.forEach(word => visitedRecord[word] === false)
let queue = [beginWord]
while (queue.length) {
result++
const tmpQ = []
while (queue.length) {
const start = queue.pop()
for (let i = 0; i < wordList.length; i++) {
if (visitedRecord[wordList[i]]) continue
if (canTransformed(start, wordList[i])) {
visitedRecord[wordList[i]] = true
tmpQ.push(wordList[i])
if (wordList[i] === endWord) return result
}
}
}
queue = tmpQ
}
return 0
};
function canTransformed(word, target) {
let equalLength = 0
for (let i = 0; i < word.length; i++) {
if (word[i] === target[i]) {
equalLength++
}
}
return word.length - equalLength === 1
}