def customdijkstra(G, start, cutoff): distances = {node: float('inf') for node in…
- User
def custom_dijkstra(G, start, cutoff): distances = {node: float('inf') for node in G.nodes()} distances[start] = 0 priority_queue = [(0, start)] # (distance, node) path_lengths = {}
codewhile priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > cutoff: continue # 超过截止值则跳过 path_lengths[current_node] = current_distance # 记录当前节点的路径长度 for neighbor, attributes in G[current_node].items(): weight = attributes.get('weight', 1.0) # 默认权重是1.0 distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return path_lengthsdef box_covering_algorithm2(G): box_sizes = np.arange(2, 30) # 设定盒子大小范围 num_boxes = []
codefor box_size in box_sizes: uncovered_nodes = set(G.nodes()) centers = [] boxes = [] while uncovered_nodes: max_mass = 0 max_mass_node = None for node in uncovered_nodes: # 使用自定义 Dijkstra 算法计算路径长度 path_lengths = custom_dijkstra(G, node, box_size - 1) mass = len([n for n in path_lengths if n in uncovered_nodes]) if mass > max_mass: max_mass = mass max_mass_node = node if max_mass_node is None: break # 如果找不到中心节点,退出循环 centers.append(max_mass_node) # 计算当前节点的箱子 box = set(n for n, d in path_lengths.items() if d <= (box_size - 1) // 2) boxes.append(box) uncovered_nodes -= box num_boxes.append(len(boxes)) return box_sizes, num_boxes - Assistant