Imagine you're an architect tasked with designing a floor plan where rooms must be arranged in a perfect rectangular grid, and hallways connect specific rooms as specified in your blueprint.
You're given a 2D integer array edges representing an undirected graph with n nodes, where edges[i] = [ui, vi] denotes a connection between nodes ui and vi.
Your challenge is to construct a 2D grid that satisfies these strict conditions:
- The grid contains all nodes from 0 to n-1, with each node appearing exactly once
- Two nodes are adjacent in the grid (horizontally or vertically) if and only if there's an edge between them
- No diagonal connections are allowed - only up, down, left, right adjacency
The problem guarantees that such a valid 2D grid layout always exists for the given edges.
Goal: Return any valid 2D integer array representing this grid layout.
Input & Output
Time & Space Complexity
Each node is visited exactly once during BFS traversal
Space for adjacency list, visited set, and result grid
Constraints
- 1 โค n โค 5 ร 104
- 0 โค edges.length โค 5 ร 104
- edges[i].length == 2
- 0 โค ui, vi < n
- ui โ vi
- The given edges can always form a valid 2D grid