📅  最后修改于: 2023-12-03 15:27:35.705000             🧑  作者: Mango
这个主题需要我们编写一个程序,在给定树中,统计给定节点之间的所有质数权重节点的个数。
给定一个树,每个节点有一个权值(正整数),要求统计给定两个节点之间的所有质数节点的个数。
例如,对于下面这个树:
1
/ \
2 3
/ | \
4 5 6
如果给定节点1和节点5,那么所有质数节点的权值为2和5,因此统计结果为2。
我们可以使用深度优先搜索(DFS)来遍历整个树,统计所有质数权重的节点个数。
首先,我们需要一个函数来判断一个数是否是质数。这个函数可以通过试除法来实现:
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
接下来,我们编写一个DFS函数,以及一个用于计数的计数器:
def count_primes(start, end, graph):
count = 0
visited = [False] * len(graph)
def dfs(node):
nonlocal count, visited
visited[node] = True
if is_prime(graph[node]):
count += 1
for neighbor in graph[node]:
if not visited[neighbor]:
dfs(neighbor)
dfs(start)
return count
最后,我们可以直接调用DFS函数进行计数,得到统计结果:
graph = [[2], [4, 5, 6], [], [], [], [], []]
start, end = 1, 5
result = count_primes(start, end, graph)
print('The number of prime nodes between node {} and node {} is {}'.format(start, end, result))
Markdown 格式的返回结果如下:
The number of prime nodes between node 1 and node 5 is 2
本文介绍了如何使用DFS算法在给定的树中统计给定节点之间的所有质数权重节点的个数。通过实现is_prime函数和DFS函数,我们可以很方便地解决这个问题。