-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadder.cs
More file actions
60 lines (52 loc) · 1.73 KB
/
Copy pathWordLadder.cs
File metadata and controls
60 lines (52 loc) · 1.73 KB
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
using System.Collections.Generic;
namespace ClassLibrary2
{
public class WordLadder
{
public static int FindLadders(string beginWord, string endWord, HashSet<string> wordList)
{
if (wordList == null || wordList.Count == 0)
{
return 0;
}
var queue = new Queue<string>();
queue.Enqueue(beginWord);
wordList.Remove(beginWord);
var res = 1;
char[] letters = new char['z' - 'a' + 1];
for (int i = 0; i < letters.Length; i++)
{
letters[i] = (char)((int)'a' + i);
}
while (queue.Count > 0)
{
int n = queue.Count;
for (int i = 0; i < n; i++)
{
var pop = queue.Dequeue();
foreach (var c in letters)
{
for (var j = 0; j < pop.Length; j++)
{
if (c != pop[j])
{
var tmp = pop.Substring(0, j) + c + pop.Substring(j + 1);
if (tmp.Equals(endWord))
{
return res + 1;
}
if (wordList.Contains(tmp))
{
queue.Enqueue(tmp);
wordList.Remove(tmp);
}
}
}
}
}
res += 1;
}
return 0;
}
}
}