Python实现图遍历
#coding=utf-8 def dfs(G,s): Q=[] S=set() Q.append(s) while Q: u=Q.pop() if u in S: continue S.add(u) Q.extend(G[u]) yield u def createGraph(pairlist): graph = {} keys = set() for index in pairlist: keys.add(index[0]) keys.add(index[1]) for key in keys: graph[key] = set() for index in pairlist: graph[index[0]].add(index[1]) graph[index[1]].add(index[0]) graph[index[0]].add(index[0]) graph[index[1]].add(index[1]) print("顶点的个数为:",len(keys)) return graph def getLinkInfo(graph): #使用集合来存放已访问过的节点 looked = set() #标记序号 i = 0 for keys in list(graph.keys()): #判断该节点是否已经访问(已经归属于某一个链路) if keys in looked: del graph[keys] continue else: result = set(list(dfs(graph, keys))) looked = looked.union(result) i = i + 1 print('--------第'+str(i)+'号-------共'+str(len(result))+'名成员') for keyidvalue in result: print(str(i)+','+keyidvalue) #可以理解为任务依赖圈 data = [('A','B'),('B','G'),('D','E'),('C','C')] pairlist = [] for index in data: pairlist.append(list(index)) graph = createGraph(pairlist) print(graph) getLinkInfo(graph)View Code