[英]How to count all of the shortest paths between 2 vertices?
因此,如果我在圖形中有兩個頂點,並且它們通過多個邊連接,而它們之間的路徑最短(即,如果我有節點A和節點B,並且它們通過三個邊直接連接(最短3個)它們之間的距離均為1),因此計數應返回3)如何修改BFS算法來實現? 這是我的代碼,它僅計算2個節點之間的最短路徑,而不計算這些最短路徑的數量。
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();
foreach (string h in g.adjacentTo(j))
{
if (!dist.ContainsKey(h))
{
q.Enqueue(h);
dist.Add(h, 1 + dist[j]);
}
if (j == p)
{
Console.WriteLine(" " + dist[j]);
return;
}
}
}
}
在foreach
之前,初始化一個變量int pathCount = 0;
然后,而不是return;
增加pathCount
。
在foreach
,檢查pathCount > 0
,如果是,則將其返回。 當然,您必須將返回類型更改為int
。
如果一個節點u有x條最短路徑,則通過它發現的相鄰節點v將具有x倍y條最短路徑,其中y是從u到v的邊數。此外,如果v通過其他相鄰節點可達(相同的路徑長度),則其最短路徑的計數將是為每個父級計算的所有xy因子的總和。
因此,該算法將與您的原型完全不同。 我建議使用一個主循環,該循環會在每次迭代中增加當前長度,然后通過查看隊列中節點的所有未訪問相鄰節點,計算每個相鄰節點的xy因子之和來處理隊列。清除隊列並將所有相鄰節點放入隊列(並將它們標記為可見),以進行下一次迭代。 在第一次迭代中,路徑長度為0,並且隊列僅包含源節點。
public void BFSDegree(Graph g, string s, string p)
{
Queue<string> q = new Queue<string>();
HashMap<string, int> path_counts = new HashMap<string, int>();
path_counts.put(s, 1);
q.Enqueue(s);
while (q.size()>0)
{
HashMap<string, int> adj_nodes = new HashMap<string, int>();
foreach (string j in q)
{
foreach (string h in g.adjacentTo(j))
{
if (!path_counts.ContainsKey(h))
{
int count = 0;
if (adj_nodes.containsKey(h))
count=adj_nodes.get(h);
count += path_counts.get(j);
adj_nodes.put(h, count);
}
}
}
if (adj_nodes.containsKey(p))
{
Console.WriteLine(" " + adj_nodes.get(p));
return;
}
path_counts.putAll(adj_nodes);
q.clear();
q.addAll(adj_nodes.keySet());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.