Approach
Sorting and greedy selection
For Construct 2D Grid Matching Graph Layout, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 48 lines of Python from the credited upstream file 3311.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def constructGridLayout(self, n: int, edges: list[list[int]]) -> list[list[int]]:3 graph = [[] for _ in range(n)]4 5 for u, v in edges:6 graph[u].append(v)7 graph[v].append(u)8 9 10 corner = min(range(len(graph)), key=lambda x: len(graph[x]))11 12 seen = {corner}13 firstRow = self._getFirstRow(graph, corner, seen)14 cols = len(firstRow)15 rows = n cols16 17 ans = [[0] * cols for _ in range(rows)]18 ans[0] = firstRow19 20 for i in range(1, rows):21 for j in range(cols):22 for v in graph[ans[i - 1][j]]:23 if v not in seen:24 ans[i][j] = v25 seen.add(v)26 break27 28 return ans29 30 def _getFirstRow(31 self,32 graph: list[list[int]],33 corner: int,34 seen: set[int]35 ) -> list[int]:36 cornerDegree = len(graph[corner])37 row = [corner]38 39 while len(row) == 1 or len(graph[row[-1]]) == cornerDegree + 1:40 41 graph[row[-1]].sort(key=lambda x: len(graph[x]))42 for v in graph[row[-1]]:43 if v not in seen and len(graph[v]) in (cornerDegree, cornerDegree + 1):44 row.append(v)45 seen.add(v)46 break47 return row48