-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0127-word-ladder.cs
73 lines (61 loc) · 2 KB
/
0127-word-ladder.cs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class Solution
{
//T: O(N^2*M) where N is the length of the word, M is total no. of words
//S: O(N^2*M) where N is the length of the word, M is total no. of words
public int LadderLength(string beginWord, string endWord, IList<string> wordList)
{
if (!wordList.Contains(endWord))
{
return 0;
}
var nei = new Dictionary<string,
HashSet<string>>();
if (!wordList.Contains(beginWord))
wordList.Add(beginWord);
foreach (var word in wordList)
{
for (var j = 0; j < word.Length; j++)
{
var pattern = word.Substring(0, j) + "*" + word.Substring(j + 1);
nei.TryAdd(pattern, new HashSet<string>());
nei[pattern].Add(word);
}
}
foreach (var neiWord in nei.Keys)
{
foreach (var val in nei[neiWord])
{
Console.WriteLine("neiWord : " + neiWord + " val : " + val);
}
}
var visited = new HashSet<string>();
visited.Add(beginWord);
var queue = new Queue<string>();
queue.Enqueue(beginWord);
var result = 1;
while (queue.Count > 0)
{
var count = queue.Count;
for (var i = 0; i < count; i++)
{
var item = queue.Dequeue();
if (string.Equals(item, endWord))
return result;
for (var j = 0; j < item.Length; j++)
{
var pattern = item.Substring(0, j) + "*" + item.Substring(j + 1);
foreach (var neiWord in nei[pattern])
{
if (!visited.Contains(neiWord))
{
queue.Enqueue(neiWord);
visited.Add(neiWord);
}
}
}
}
result += 1;
}
return 0;
}
}