3311. Construct 2D Grid Matching Graph Layout
3311. Construct 2D Grid Matching Graph Layout
Description
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
0
ton - 1
in 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.
Example 1:
1 | Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]] |
Explanation:
![](https://assets.leetcode.com/uploads/2024/08/11/screenshot-from-2024-08-11-14-07-59.png)
Example 2:
1 | Input: n = 5, edges = [[0,1],[1,3],[2,3],[2,4]] |
Explanation:
![](https://assets.leetcode.com/uploads/2024/08/11/screenshot-from-2024-08-11-14-06-02.png)
Example 3:
1 | Input: n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]] |
Explanation:
![](https://assets.leetcode.com/uploads/2024/08/11/screenshot-from-2024-08-11-14-06-38.png)
Constraints:
2 <= n <= 5 * 10^4
1 <= edges.length <= 10^5
edges[i] = [u<sub>i</sub>, v<sub>i</sub>]
0 <= u<sub>i</sub> < v<sub>i</sub> < n
- All the edges are distinct.
- The input is generated such that
edges
can form a 2D grid that satisfies the conditions.
Hints/Notes
- 2024/09/22
- jigsaw puzzle
- 0x3Fâs solution(checked)
- Weekly Contest 418
Solution
Language: C++
1 | class Solution { |