You're given an undirected graph with n nodes labeled from 1 to n, and your mission is to organize these nodes into groups with a special constraint.
Think of it like organizing people at a party where friends must be in adjacent groups - if two people are friends (connected by an edge), they can only be in groups that differ by exactly 1 (like group 2 and group 3, but not group 1 and group 3).
Your goal: Find the maximum number of groups you can create while satisfying this constraint. If it's impossible to group the nodes this way, return -1.
Key constraint: For every edge [a, b], if node a is in group x and node b is in group y, then |y - x| = 1.
This is essentially asking: what's the longest path in each connected component of the graph, since nodes along a path can be arranged in consecutive groups!
Input & Output
Visualization
Time & Space Complexity
Visit each vertex and edge once during BFS traversal of all components
Space for adjacency list, visited array, and BFS queue
Constraints
- 1 โค n โค 500
- 0 โค edges.length โค 104
- edges[i].length == 2
- 1 โค ai, bi โค n
- ai != bi
- No duplicate edges in the input