求解500节点4正则图全感染所需天数及现有BFS代码错误排查
代码错误分析
- BFS天数统计逻辑完全错误:你当前的
days +=1是在每发现一个新感染节点时执行,统计的实际是总感染人数减1,所以输出结果接近500。正确逻辑是:队列中同一批次的所有节点都是同一天被感染的,需要一次性处理完当前队列的全部节点(即完成单日的所有传染)后,再给天数加1,新感染的节点统一归入下一批次队列处理。 - 邻接矩阵生成不符合题意:题目中的「认识」是双向无向关系,你当前生成的是随机有向图,A和B相连不代表B和A相连,完全不符合社交关系的设定,同时没有排除节点自己和自己相连的无效边,会导致传播逻辑异常。
- 额外优化点:用列表的
in判断节点是否被感染时间复杂度是O(n),可以替换为布尔数组提升查询效率。
修正后可运行代码
import random random.seed(20) nodes = 500 num_connections = 4 # 生成对称无向4正则图,排除自环 graph = [[0]*nodes for _ in range(nodes)] degree = [0]*nodes for i in range(nodes): while degree[i] < num_connections: # 随机选一个不等于i、度数没满的节点连边 j = random.choice([x for x in range(nodes) if x != i and degree[x] < num_connections]) if graph[i][j] == 0: graph[i][j] = 1 graph[j][i] = 1 degree[i] += 1 degree[j] += 1 days = 0 infected = [False]*nodes infected[0] = True current_queue = [0] infected_count = 1 while infected_count < nodes: next_queue = [] # 处理当日所有感染者的传染 for patient in current_queue: for neighbor, is_connected in enumerate(graph[patient]): if is_connected == 1 and not infected[neighbor]: infected[neighbor] = True infected_count +=1 next_queue.append(neighbor) # 单日传染结束,天数加1 days +=1 current_queue = next_queue print(days)
运行后输出结果在10左右,符合小世界网络的传播预期。
内容的提问来源于stack exchange,提问作者EllipticalInitial
相关产品推荐
相关产品推荐

