[英]Faster algorithm for finding number of paths between two nodes
我试图用Python回答在线法官的问题,但是我同时超出了时间限制和内存限制。 问题是几乎要询问从起始节点到结束节点的所有路径数。 完整的问题说明可以在这里看到。
这是我的代码:
import sys
lines = sys.stdin.read().strip().split('\n')
n = int(lines[0])
dict1 = {}
for i in xrange(1, n+1):
dict1[i] = []
for i in xrange(1, len(lines) - 1):
numbers = map(int, lines[i].split())
num1 = numbers[0]
num2 = numbers[1]
dict1[num2].append(num1)
def pathfinder(start, graph, count):
new = []
if start == []:
return count
for i in start:
numList = graph[i]
for j in numList:
if j == 1:
count += 1
else:
new.append(j)
return pathfinder(new, graph, count)
print pathfinder([n], dict1, 0)
该代码的作用是从末端节点开始,并通过探索所有相邻节点一直到顶部。 我基本上做了一个广度优先的搜索算法,但是它占用了太多的空间和时间。 如何改进此代码以使其更高效? 我的方法错误吗,应该如何解决?
由于图是非循环的,因此存在拓扑顺序,我们可以立即看到它是1, 2, ..., n
。 因此我们可以像解决最长路径问题一样使用动态编程。 在列表paths
,元素paths[i]
存储从1
到i
会有多少个路径。 更新将很简单-对于每个边缘(i,j)
,其中i
是我们的拓扑顺序,我们执行paths[j] += path[i]
。
from collections import defaultdict
graph = defaultdict(list)
n = int(input())
while True:
tokens = input().split()
a, b = int(tokens[0]), int(tokens[1])
if a == 0:
break
graph[a].append(b)
paths = [0] * (n+1)
paths[1] = 1
for i in range(1, n+1):
for j in graph[i]:
paths[j] += paths[i]
print(paths[n])
请注意,您实现的实际上不是BFS
因为您不会标记访问过的顶点,从而使start
时的比例不成比例。
测试图
for i in range(1, n+1):
dict1[i] = list(range(i-1, 0, -1))
如果打印start
尺寸,您会看到给定n
的最大值正好以二项式(n,floor(n / 2))增长,即〜4 ^ n / sqrt(n)。 还要注意, BFS
不是您想要的,因为无法以这种方式计算路径数量。
import sys
from collections import defaultdict
def build_matrix(filename, x):
# A[i] stores number of paths from node x to node i.
# O(n) to build parents_of_node
parents_of_node = defaultdict(list)
with open(filename) as infile:
num_nodes = int(infile.readline())
A = [0] * (num_nodes + 1) # A[0] is dummy variable. Not used.
for line in infile:
if line == "0 0":
break
u, v = map(int, line.strip().split())
parents_of_node[v].append(u)
# Initialize all direct descendants of x to 1
if u == x:
A[v] = 1
# Number of paths from x to i = sum(number of paths from x to parent of i)
for i in xrange(1, num_nodes + 1): # O(n)
A[i] += sum(A[p] for p in parents_of_node[i]) # O(max fan-in of graph), assuming O(1) for accessing dict.
# Total time complexity to build A is O(n * (max_fan-in of graph))
return A
def main():
filename = sys.argv[1]
x = 1 # Find number of paths from x
y = 4 # to y
A = build_matrix(filename, x)
print(A[y])
您正在执行的是该代码中的DFS(而非BFS)...
这是一个好的解决方案的链接...编辑:请改用此方法...
http://www.geeksforgeeks.org/find-paths-given-source-destination/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.