I have a graph:
G = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'E]),
'D': set(['B']),
'E': set(['B', 'C']),
'F': set(['G'])}
I want to get all the distinct neighbors'combinations of each nodes in this graph. The result will be like this:
['A','B','C','D','E']
['F','G']
I tried the BFS and I used a loop to traverse all the nodes, it worked but imagining the graph is very big and it will take too long. Do you have any advice?
Here is my code:
# define bfs
def bfs(graph, node):
# node is the starting position
# graph is the graph in dictionary format
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
for x in graph[s]:
if x not in visited:
visited.append(x)
queue.append(x)
return visited
# define is_exist_in_list
def is_exist_in_list(target, element):
for line in target:
if element in line:
return True
return False
res = []
for i in G.nodes:
if is_exist_in_list(res, i) == False:
tt = bfs(G, i)
tt.sort()
if tt not in res:
res.append(tt)