Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d66b10c

Browse files
author
zhangbo
committed
19/09/13
1 parent 68541e4 commit d66b10c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎127.word-ladder.js‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {string} beginWord
3+
* @param {string} endWord
4+
* @param {string[]} wordList
5+
* @return {number}
6+
*/
7+
var ladderLength = function (beginWord, endWord, wordList) {
8+
if (!wordList.includes(endWord)) return 0
9+
const visitedRecord = {}
10+
let result = 1
11+
wordList.forEach(word => visitedRecord[word] === false)
12+
let queue = [beginWord]
13+
while (queue.length) {
14+
result++
15+
const tmpQ = []
16+
while (queue.length) {
17+
const start = queue.pop()
18+
for (let i = 0; i < wordList.length; i++) {
19+
if (visitedRecord[wordList[i]]) continue
20+
if (canTransformed(start, wordList[i])) {
21+
visitedRecord[wordList[i]] = true
22+
tmpQ.push(wordList[i])
23+
if (wordList[i] === endWord) return result
24+
}
25+
}
26+
}
27+
queue = tmpQ
28+
}
29+
return 0
30+
};
31+
32+
33+
function canTransformed(word, target) {
34+
let equalLength = 0
35+
for (let i = 0; i < word.length; i++) {
36+
if (word[i] === target[i]) {
37+
equalLength++
38+
}
39+
}
40+
return word.length - equalLength === 1
41+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /