Đây là mã C# để giải quyết vấn đề bằng BFS:
//use a hash set for a fast check if a word is already in the dictionary
static HashSet<string> Dictionary = new HashSet<string>();
//dictionary used to find the parent in every node in the graph and to avoid traversing an already traversed node
static Dictionary<string, string> parents = new Dictionary<string, string>();
public static List<string> FindPath(List<string> input, string start, string end)
{
char[] allcharacters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
foreach (string s in input)
Dictionary.Add(s);
List<string> currentFrontier = new List<string>();
List<string> nextFrontier = new List<string>();
currentFrontier.Add(start);
while (currentFrontier.Count > 0)
{
foreach (string s in currentFrontier)
{
for (int i = 0; i < s.Length; i++)
{
foreach (char c in allcharacters)
{
StringBuilder newWordBuilder = new StringBuilder(s);
newWordBuilder[i] = c;
string newWord = newWordBuilder.ToString();
if (Dictionary.Contains(newWord))
{
//avoid traversing a previously traversed node
if (!parents.Keys.Contains(newWord))
{
parents.Add(newWord.ToString(), s);
nextFrontier.Add(newWord);
}
}
if (newWord.ToString() == end)
{
return ExtractPath(start, end);
}
}
}
}
currentFrontier.Clear();
currentFrontier.Concat(nextFrontier);
nextFrontier.Clear();
}
throw new ArgumentException("The given dictionary cannot be used to get a path from start to end");
}
private static List<string> ExtractPath(string start,string end)
{
List<string> path = new List<string>();
string current = end;
path.Add(end);
while (current != start)
{
current = parents[current];
path.Add(current);
}
path.Reverse();
return path;
}
Nguồn
2014-04-10 20:18:09
đồ thị này đang thực sự được sử dụng trên tại Việt Nga, xem http://ru.wiktionary.org/w/ index.php? title =% D0% A1% D0% BB% D1% 83% D0% B6% D0% B5% D0% B1% D0% BD% D0% B0% D1% 8F% 3 Tìm kiếm & ns6 = 1 & tìm kiếm =% D0% BC% D0% B5% D1% 82% D0% B0% D0% B3% D1% 80% D0% B0% D0% BC% D0% BC & fulltext =% D0% A0% D0% B0% D1% 81% D1% 88 % D0% B8% D1% 80% D0% B5% D0% BD% D0% BD% D1% 8B% D0% B9 +% D0%% BF% D0% BE% D0% B8% D1% 81% D0% BA hoặc http : //www.aisee.com/graph_of_the_month/words.htm –
@RegDwight: Cảm ơn :) – codaddict
Đây chính xác là những gì tôi có trong đầu. Tôi đã suy nghĩ nhiều hơn về không gian và thời gian phức tạp. – Srikanth