Loading content...
You are tasked with organizing nodes in an undirected graph into hierarchical layers. Given a positive integer n representing the number of nodes (labeled from 1 to n), and a 2D integer array edges where each edges[i] = [uᵢ, vᵢ] indicates an undirected edge between nodes uᵢ and vᵢ, your goal is to assign each node to exactly one layer such that the following conditions are satisfied:
The layers are indexed starting from 1. Note that the graph may consist of multiple disconnected components.
Return the maximum number of layers into which the nodes can be organized while satisfying all conditions. If no valid layering arrangement exists that satisfies the constraints, return -1.
n = 6
edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]4One optimal layering is:
Every edge connects nodes in adjacent layers (layer difference of exactly 1). For example, edge [1,2] connects layer 2 and layer 3, edge [2,6] connects layer 3 and layer 4. This arrangement uses 4 layers, which is the maximum possible.
n = 3
edges = [[1,2],[2,3],[3,1]]-1The graph forms a triangle (3-cycle). If we place node 1 in layer x, node 2 must be in layer x+1, and node 3 must be in layer x+2. However, the edge [3,1] requires |x - (x+2)| = 1, which is impossible since |2| ≠ 1. This odd-length cycle makes any valid layering impossible.
n = 4
edges = [[1,2],[2,3],[3,4]]4The graph forms a simple path: 1—2—3—4. The optimal layering assigns each node to a distinct layer in sequence:
Each edge connects consecutive layers, maximizing the total to 4 layers.
Constraints