File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ var ladderLength = function ( beginWord , endWord , wordList ) {
2+ if ( ! wordList . includes ( endWord ) ) return 0 ;
3+ let patternMap = { } ;
4+ wordList . push ( beginWord ) ;
5+
6+ for ( let word of wordList ) {
7+ for ( let x = 0 ; x < word . length ; x ++ ) {
8+ const pattern = word . slice ( 0 , x ) + "*" + word . slice ( x + 1 ) ;
9+ patternMap [ pattern ] = patternMap [ pattern ] || [ ] ;
10+ patternMap [ pattern ] . push ( word ) ;
11+ }
12+ }
13+
14+ let wordCount = 1 ,
15+ queue = [ beginWord ] ,
16+ visited = [ beginWord ] ;
17+ while ( queue . length ) {
18+ const levelSize = queue . length ;
19+ for ( let x = 0 ; x < levelSize ; x ++ ) {
20+ const word = queue . shift ( ) ;
21+ if ( word === endWord ) return wordCount ;
22+ for ( let x = 0 ; x < word . length ; x ++ ) {
23+ const pattern = word . slice ( 0 , x ) + "*" + word . slice ( x + 1 ) ;
24+ for ( let nei of patternMap [ pattern ] ) {
25+ if ( nei in visited ) continue ;
26+ visited [ nei ] = true ;
27+ queue . push ( nei ) ;
28+ }
29+ }
30+ }
31+ wordCount += 1 ;
32+ }
33+ return 0 ;
34+ } ;
You can’t perform that action at this time.
0 commit comments