Approach
Breadth-first search
For Divide Nodes into the Maximum Number of Groups, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 124 lines of Python from the credited upstream file divide-nodes-into-the-maximum-number-of-groups.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def magnificentSets(self, n, edges):7 """8 :type n: int9 :type edges: List[List[int]]10 :rtype: int11 """12 def iter_dfs(u):13 group = []14 stk = [u]15 lookup[u] = 016 while stk:17 u = stk.pop()18 group.append(u)19 for v in adj[u]:20 if lookup[v] != -1:21 if lookup[v] == lookup[u]: 22 return []23 continue24 lookup[v] = lookup[u]^125 stk.append(v)26 return group27 28 def bfs(u):29 result = 030 lookup = [False]*n31 q = [u]32 lookup[u] = True33 while q:34 new_q = []35 for u in q:36 for v in adj[u]:37 if lookup[v]:38 continue39 lookup[v] = True40 new_q.append(v)41 q = new_q42 result += 143 return result44 45 adj = [[] for _ in xrange(n)]46 for u, v in edges:47 adj[u-1].append(v-1)48 adj[v-1].append(u-1)49 result = 050 lookup = [-1]*n51 for u in xrange(n):52 if lookup[u] != -1:53 continue54 group = iter_dfs(u)55 if not group:56 return -157 result += max(bfs(u) for u in group)58 return result59 60 61626364class Solution2(object):65 def magnificentSets(self, n, edges):66 """67 :type n: int68 :type edges: List[List[int]]69 :rtype: int70 """71 def bfs(u):72 group = []73 q = [u]74 lookup[u] = True75 while q:76 new_q = []77 for u in q:78 group.append(u)79 for v in adj[u]:80 if lookup[v]:81 continue82 lookup[v] = True83 new_q.append(v)84 q = new_q85 return group86 87 def bfs2(u):88 result = 089 lookup = [False]*n90 q = {u}91 lookup[u] = True92 while q:93 new_q = set()94 for u in q:95 for v in adj[u]:96 if v in q:97 return 098 if lookup[v]:99 continue100 lookup[v] = True101 new_q.add(v)102 q = new_q103 result += 1104 return result105 106 adj = [[] for _ in xrange(n)]107 for u, v in edges:108 adj[u-1].append(v-1)109 adj[v-1].append(u-1)110 result = 0111 lookup = [0]*n112 for u in xrange(n):113 if lookup[u]:114 continue115 group = bfs(u)116 mx = 0117 for u in group:118 d = bfs2(u)119 if d == 0:120 return -1121 mx = max(mx, d)122 result += mx123 return result124