I have an undirected graph and I need to reorder its vertices into a permutation that satisfies the following “prefix-neighbors” property:
Property: For every vertex v_i (with i > 0) in the permutation, if there exists any vertex v_j (with j < i) that is adjacent to v_i (i.e., (v_j, v_i) is an edge in E), then every vertex v_k with k < j must also be adjacent to v_i.
In other words, if has any neighbors among the vertices that come before it in the ordering, then those neighbors must form a contiguous block starting from the very first vertex in the ordering.
For example, consider a graph with vertices and edges: (0,1) (0,2) (1,3) (2,3)
0 / \ 1 2 \ / 3
One valid ordering is [1, 2, 0, 3]:
- Vertex 1: Placed first, so no condition applies.
- Vertex 2: Placed second; if it has any neighbor among vertices before it, then the very first vertex must be adjacent—but here it happens that 2 is not adjacent to 1, so the condition is not triggered.
- Vertex 0: Placed third; its neighbors among are 1 and 2. The earliest (lowest-index) neighbor is 1, which is at the beginning of the ordering.
- Vertex 3: Placed last; its neighbors among are 1 and 2 (its first neighbor is 1 at index 0), so the condition is satisfied.
My questions are:
- Algorithm & Complexity: Is it possible to compute such a permutation in time?
- Approach:What algorithm would you recommend for this problem?
- Uniqueness:Under what conditions is such an ordering unique, and how can I detect if multiple valid orders exist or if no valid ordering exists?
Any algorithm sketches, insights, or sample code in Python or C++ would be greatly appreciated!