📅  最后修改于: 2023-12-03 15:25:45.386000             🧑  作者: Mango
本篇介绍如何找到一个无向图中具有最大和最小度数的节点,并打印出它们的信息。
class Node:
def __init__(self, value):
self.value = value
self.neighbors = []
def add_neighbor(self, node):
self.neighbors.append(node)
class UndirectedGraph:
def __init__(self, nodes):
self.nodes = nodes
def get_max_degree_node(self):
max_degree_node = None
max_degree = float("-inf")
for node in self.nodes:
degree = len(node.neighbors)
if degree > max_degree:
max_degree = degree
max_degree_node = node
return max_degree_node, max_degree
def get_min_degree_node(self):
min_degree_node = None
min_degree = float("inf")
for node in self.nodes:
degree = len(node.neighbors)
if degree < min_degree:
min_degree = degree
min_degree_node = node
return min_degree_node, min_degree
def print_degree_info(self):
max_degree_node, max_degree = self.get_max_degree_node()
min_degree_node, min_degree = self.get_min_degree_node()
print(f"Max degree node: {max_degree_node.value}, degree: {max_degree}")
print(f"Min degree node: {min_degree_node.value}, degree: {min_degree}")
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n1.add_neighbor(n2)
n1.add_neighbor(n3)
n2.add_neighbor(n1)
n2.add_neighbor(n3)
n2.add_neighbor(n4)
n3.add_neighbor(n1)
n3.add_neighbor(n2)
n3.add_neighbor(n4)
n3.add_neighbor(n5)
n4.add_neighbor(n2)
n4.add_neighbor(n3)
n5.add_neighbor(n3)
g = UndirectedGraph([n1, n2, n3, n4, n5])
g.print_degree_info()
输出结果如下:
Max degree node: 2, degree: 3
Min degree node: 5, degree: 1
本篇介绍了如何找到一个无向图中具有最大和最小度数的节点,并打印出它们的信息。这个问题的关键在于遍历所有节点,计算它们的度数,并记录最大和最小度数以及它们所对应的节点。这个问题在实际应用中主要用于网络分析、社交网络分析等领域。