-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path127wordLadder.cs
97 lines (86 loc) · 2.95 KB
/
127wordLadder.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wordLadder
{
class Program
{
static void Main(string[] args)
{
/*
* Latest update: June 19, 2015
* Test case:
* start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
*/
HashSet<string> hs = new HashSet<string>{"hit", "hot", "dot", "dog", "cog"};
int result = ladderLength("hit", "cog", hs);
}
/**
* Latest update: June 19, 2015
* Try to learn how to code in 10 minutes in C# using other people's idea and code
*
* code source:
* http://shanjiaxin.blogspot.ca/2014/04/word-ladder-leetcode.html
*
* Bug: Time Limit Exceeded
*/
public static int ladderLength(String beginWord, String endWord, ISet<String> wordDict)
{
if (beginWord == null || endWord == null || wordDict == null || wordDict.Count == 0)
{
return 0;
}
Queue<String> queue = new Queue<string>();
queue.Enqueue(beginWord);
wordDict.Remove(beginWord);
int length = 1;
while ( queue.Count > 0 )
{
int count = queue.Count;
// Check each adjacent string
for (int i = 0; i < count; i++) // julia comment: BFS, each layer visit each node
{
String current = queue.Dequeue();
// Check if there's adjacent string
for (int j = 0; j < current.Length; j++)
{
for (char c = 'a'; c <= 'z'; c++)
{
if (c == current[j])
{
continue;
}
String temp = replace(current, j, c);
if (temp.CompareTo(endWord) ==0)
{
return length + 1;
}
if (wordDict.Contains(temp))
{
queue.Enqueue(temp);
wordDict.Remove(temp);
}
}
}
}
length++; // julia comment: BFS, go to next layer
}
return 0;
}
private static String replace(String s, int index, char c)
{
char[] chars = s.ToCharArray();
chars[index] = c;
return new String(chars);
}
/**
* http://www.programcreek.com/2012/12/leetcode-word-ladder/
*/
}
}