【发布时间】:2015-12-26 23:41:24
【问题描述】:
所以我正在尝试制作 BFS 算法,并且能够计算出每 2 个节点之间的最短路径距离。但是每个节点(即节点 A)的邻居不仅是节点,它还是作为键的节点字典和每两个节点参与的匹配哈希集。现在,我不知道如何在 BFS 时存储路径正在工作......这是返回每个节点的邻居的邻接函数
Dictionary<string, Dictionary<string, HashSet<string>>> dic= new Dictionary<string, Dictionary < string,, HashSet < string >>>;
public IEnumerable<KeyValuePair<string, HashSet<string>>> adjacentto(string v)
{
return dic[v];
}
这是我的 BFS 函数:
private Dictionary<string, int> dist = new Dictionary<string, int>();
public void BFSDegree(Graph g, string s, string p)
{
Queue<string> q = new Queue<string>();
dist.Add(s, 0);
q.Enqueue(s);
while (q.Count() != 0)
{
string j = q.Dequeue();
//count = 0;
foreach (KeyValuePair<string, HashSet<string>> h in g.adjacentto(j))
{
if (!dist.ContainsKey(h.Key))
{
q.Enqueue(h.Key);
dist.Add(h.Key, 1 + dist[j]);
}
if (j == p)
{
Console.WriteLine(" " + dist[j]);
return;
}
}
}
}
所以,我需要的是去查看路径并读取哈希集的值,例如节点 A 和节点 B 一起玩了 3 场比赛,比赛 1,比赛 2,比赛 7,所以这应该是路径。所以我要打印到控制台“路径是匹配 1、匹配 2 或匹配 7)。如果我有 2 个节点没有一起出现在匹配中,但它们都与节点 A 一起出现在2 个单独的匹配项,因此路径应该通过这 2 个匹配项中的任何一个。在操作 BFS 时如何跟踪路径并存储路径?这是我正在从中读取图表的文件。
通过使用 BFS,我能够实现第一个目标(学位)。但现在我不知道如何实现“链”或路径。链条只是路径中电影的数量,所以我认为如果我能够在 BFS 工作时保存路径(显示路径),我将能够实现链条。所以我的问题是我如何保存路径并显示它的最后一个目标。
【问题讨论】:
-
你的问题很难理解。你能举例说明你的意思吗?也许举个例子说明你的图表会是什么样子以及结果?
-
我编辑了这个问题。希望你现在能理解我的问题。
标签: c# graph breadth-first-search