Jeremiah Willcock的answer是正確的,但細節。這是DAG的線性時間算法。
for each node v, initialize num_paths[v] = 0
let t be the destination and set num_paths[t] = 1
for each node v in reverse topological order (sinks before sources):
for each successor w of v:
set num_paths[v] = num_paths[v] + num_paths[w]
let s be the origin and return num_paths[s]
我敢肯定,一般有向圖的問題是
#P-complete,但我無法找到除非cstheory的
unsourced question搜索的幾分鐘任何東西。
好的,這是一些僞代碼。我已經將前面的算法的內容與拓撲排序相結合,並添加了一些循環檢測邏輯。在s
和t
之間的循環的情況下,num_paths
的值可能不準確,但取決於t
是否可到達將爲零非零。一個循環中的每個節點都不會有in_cycle
設置爲true,但是每當一個SCC根(在Tarjan的SCC算法中)就足以觸發提前退出,當且僅當s和t之間存在循環時。
REVISED ALGORITHM
let the origin be s
let the destination be t
for each node v, initialize
color[v] = WHITE
num_paths[v] = 0
in_cycle[v] = FALSE
num_paths[t] = 1
let P be an empty stack
push (ENTER, s) onto P
while P is not empty:
pop (op, v) from P
if op == ENTER:
if color[v] == WHITE:
color[v] = GRAY
push (LEAVE, v) onto P
for each successor w of v:
push (ENTER, w) onto P
else if color[v] == GRAY:
in_cycle[v] = TRUE
else: # op == LEAVE
color[v] = BLACK
for each successor w of v:
set num_paths[v] = num_paths[v] + num_paths[w]
if num_paths[v] > 0 and in_cycle[v]:
return infinity
return num_paths[s]
我認爲你誤讀了CLRS,你會引用關於從書中找出O(n)中所有路徑的確切段落嗎? –
賽義德,恐怕我沒有誤讀。這是第614,22.4.2頁,CLRS 3版本上的練習題。 –