Construct 2D Grid Matching Graph Layout - Problem
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
example_1.py โ 2ร2 Grid
$
Input:
edges = [[0,1],[1,3],[2,3],[0,2]]
โบ
Output:
[[0,1],[2,3]]
๐ก Note:
This forms a 2ร2 grid where node 0 connects to nodes 1 and 2, node 1 connects to nodes 0 and 3, node 2 connects to nodes 0 and 3, and node 3 connects to nodes 1 and 2. The adjacency perfectly matches a rectangular grid layout.
example_2.py โ Single Row
$
Input:
edges = [[0,1],[1,2],[2,3]]
โบ
Output:
[[0,1,2,3]]
๐ก Note:
This creates a linear path that forms a 1ร4 grid (single row). Each node is connected only to its immediate neighbors in the sequence.
example_3.py โ Single Node
$
Input:
edges = []
โบ
Output:
[[0]]
๐ก Note:
With only one node and no edges, the result is a 1ร1 grid containing just node 0.
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code