3

I have a set of nodes (N=7)

{a, b, c, d, e, f, g}

These nodes form one or more distinct undirected graphs, I want to find the graph with the maximum number of nodes. However, I have a constraint that the complexity can not be more than (N*M) where M is the maximum number of edges a single node has (The node with the max edges). Here is an example of how the nodes are structured

nodes = {a: [b], b: [a, c], c: [b], d:[e, f], e: [d, f], f:[e, d, g], g:[f]}

In this example we have two undirected graphs 1. {a, b, c} and 2. {d, e, f, g}. So the answer should be 4.

For each node I can perform graph traversal, such as dfs or bfs, and this only has a complexity of O(V+E) (V number of nodes in graph and E number of edges in graph). The problem happens if there are more than one distinct undirected graphs in the node set like above (which I don't know until after runtime). I will have to loop through each node in the node set, performing dfs which leads to O(N*(V+E)), which does not satisfy the time complexity constraint. I guess once I have performed the dfs on the first graph I can remove it's nodes from the set of N nodes we are looping through (therefore reducing the loop from N to something else) but i'm not sure how this affects the time complexity mathematically? Below is the code I am using at the moment, any advice would be much appreciated. I may be overcomplicating this...

def dfs(node_set, n, vis):

   if n not in vis:
       vis.add(n)

       for n in node_set[n]:
           getDfs(node_set,n,vis)

    return visited

graphs = []

for n in nodes:
     graphs.append(getSets(nodes, n, set()))

nums = []

for g in graphs:
     nums.append(len(g))

max_num = max(nums)

>> 4
maracuja
  • 170
  • 4
  • 18

1 Answers1

0

The approach below traverses each vertex and its edges to find the complete set of vertices in each graph. You will also have to traverse the number of graphs to find the maximum number of vertices across graphs.

def findgraphs(nodes):
    graphs = []
    while nodes:
        graph = set()
        queue = set([next(iter(nodes))])
        while queue:
            nextq = set()
            graph.update(queue)
            for q in queue:
                nextq.update(n for n in nodes[q] if n not in graph)
                del nodes[q]

            queue = nextq

        graphs.append(graph)

    return graphs

nodes = {'a': ['b'], 'b': ['a', 'c'], 'c': ['b'], 'd': ['e', 'f'], 'e': ['d', 'f'], 'f': ['e', 'd', 'g'], 'g': ['f']}
graphs = findgraphs(nodes)
m = max(len(g) for g in graphs)
print(m)
# 4
benvc
  • 12,401
  • 3
  • 22
  • 45