1
+ public class Solution
2
+ {
3
+ //T: O(N^2*M) where N is the length of the word, M is total no. of words
4
+ //S: O(N^2*M) where N is the length of the word, M is total no. of words
5
+ public int LadderLength ( string beginWord , string endWord , IList < string > wordList )
6
+ {
7
+ if ( ! wordList . Contains ( endWord ) )
8
+ {
9
+ return 0 ;
10
+ }
11
+
12
+ var nei = new Dictionary < string ,
13
+ HashSet < string > > ( ) ;
14
+ if ( ! wordList . Contains ( beginWord ) )
15
+ wordList . Add ( beginWord ) ;
16
+
17
+ foreach ( var word in wordList )
18
+ {
19
+ for ( var j = 0 ; j < word . Length ; j ++ )
20
+ {
21
+ var pattern = word . Substring ( 0 , j ) + "*" + word . Substring ( j + 1 ) ;
22
+ nei . TryAdd ( pattern , new HashSet < string > ( ) ) ;
23
+ nei [ pattern ] . Add ( word ) ;
24
+ }
25
+ }
26
+
27
+ foreach ( var neiWord in nei . Keys )
28
+ {
29
+ foreach ( var val in nei [ neiWord ] )
30
+ {
31
+ Console . WriteLine ( "neiWord : " + neiWord + " val : " + val ) ;
32
+ }
33
+ }
34
+
35
+ var visited = new HashSet < string > ( ) ;
36
+ visited . Add ( beginWord ) ;
37
+
38
+ var queue = new Queue < string > ( ) ;
39
+ queue . Enqueue ( beginWord ) ;
40
+
41
+ var result = 1 ;
42
+
43
+ while ( queue . Count > 0 )
44
+ {
45
+ var count = queue . Count ;
46
+ for ( var i = 0 ; i < count ; i ++ )
47
+ {
48
+ var item = queue . Dequeue ( ) ;
49
+ if ( string . Equals ( item , endWord ) )
50
+ return result ;
51
+
52
+ for ( var j = 0 ; j < item . Length ; j ++ )
53
+ {
54
+ var pattern = item . Substring ( 0 , j ) + "*" + item . Substring ( j + 1 ) ;
55
+ foreach ( var neiWord in nei [ pattern ] )
56
+ {
57
+ if ( ! visited . Contains ( neiWord ) )
58
+ {
59
+ queue . Enqueue ( neiWord ) ;
60
+ visited . Add ( neiWord ) ;
61
+
62
+ }
63
+ }
64
+
65
+ }
66
+
67
+ }
68
+ result += 1 ;
69
+ }
70
+
71
+ return 0 ;
72
+ }
73
+ }
0 commit comments