Construct 2D Grid Matching Graph Layout - Problem
You are given a 2D integer array edges representing an undirected graph having n nodes, where edges[i] = [ui, vi] denotes an edge between nodes ui and vi.
Construct a 2D grid that satisfies these conditions:
- The grid contains all nodes from
0ton - 1in its cells, with each node appearing exactly once. - Two nodes should be in adjacent grid cells (horizontally or vertically) if and only if there is an edge between them in
edges.
It is guaranteed that edges can form a 2D grid that satisfies the conditions.
Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return any of them.
Input & Output
Example 1 — Basic 2×2 Grid
$
Input:
edges = [[0,1],[1,3],[2,3],[2,0]]
›
Output:
[[0,1],[2,3]]
💡 Note:
Nodes 0 and 3 are corners (degree 2). Starting from corner 0: build first row [0,1], then second row [2,3]. Adjacent cells match the edges: 0-1, 1-3, 3-2, 2-0.
Example 2 — Single Row
$
Input:
edges = [[0,1],[1,2],[2,3]]
›
Output:
[[0,1,2,3]]
💡 Note:
This forms a single row. Nodes 0 and 3 have degree 1 (endpoints). The path connects 0→1→2→3, so the grid is one row.
Example 3 — 1×3 Grid
$
Input:
edges = [[0,1],[1,2]]
›
Output:
[[0,1,2]]
💡 Note:
Three nodes in a line. Nodes 0 and 2 are endpoints (degree 1), node 1 is in the middle (degree 2).
Constraints
- 1 ≤ edges.length ≤ 104
- edges[i].length == 2
- 0 ≤ ui, vi ≤ 104
- All the edges are distinct
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code