0

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)
velvetrock
  • 593
  • 1
  • 8
  • 18

1 Answers1

1

It seems to me that you are working with networkx. If so, you could do:

import networkx as nx

G = nx.Graph((key, value) for key in G for value in G[key])
results = list(nx.connected_components(G))

Result:

[{'E', 'D', 'A', 'B', 'C'}, {'F', 'G'}]

If you want to build it yourself from the dictionary as provided, I wouldn't use lists but sets:

results = []
stack = set(G)
while stack:
    node = stack.pop()
    result = {node}
    check = {node}
    while check:
        node = check.pop()
        for child in G.get(node, set()) - result:
            result.add(child)
            check.add(child)
            stack.discard(child)
    results.append(result)

Result for your sample G:

[{'B', 'E', 'A', 'C', 'D'}, {'G', 'F'}]
Timus
  • 10,974
  • 5
  • 14
  • 28
  • Thanks for your reply! The first method works, but the second gives the error "AttributeError: 'Graph' object has no attribute 'get'" – velvetrock Nov 29 '21 at 13:55
  • @velvetrock The second method is for the dictionary you've provided, not the graph. – Timus Nov 29 '21 at 13:57