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
- 59 lines of Java from the credited upstream file 3311.java.
- The implementation visibly relies on sequence storage.
- 8 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 public int[][] constructGridLayout(int n, int[][] edges) {3 List<Integer>[] graph = new ArrayList[n];4 5 for (int i = 0; i < n; i++)6 graph[i] = new ArrayList<>();7 8 for (int[] edge : edges) {9 final int u = edge[0];10 final int v = edge[1];11 graph[u].add(v);12 graph[v].add(u);13 }14 15 16 int corner = 0;17 for (int i = 1; i < n; i++)18 if (graph[i].size() < graph[corner].size())19 corner = i;20 21 boolean[] seen = new boolean[n];22 seen[corner] = true;23 int[] firstRow = getFirstRow(graph, corner, seen);24 int cols = firstRow.length;25 int rows = n / cols;26 27 int[][] ans = new int[rows][cols];28 ans[0] = firstRow;29 30 for (int i = 1; i < rows; ++i)31 for (int j = 0; j < cols; ++j)32 for (final int v : graph[ans[i - 1][j]])33 if (!seen[v]) {34 ans[i][j] = v;35 seen[v] = true;36 break;37 }38 39 return ans;40 }41 42 private int[] getFirstRow(List<Integer>[] graph, int corner, boolean[] seen) {43 final int cornerDegree = graph[corner].size();44 List<Integer> row = new ArrayList<>(List.of(corner));45 46 while (row.size() == 1 || graph[row.get(row.size() - 1)].size() == cornerDegree + 1) {47 List<Integer> neighbors = graph[row.get(row.size() - 1)];48 Collections.sort(neighbors, (a, b) -> graph[a].size() - graph[b].size());49 for (final int v : neighbors)50 if (!seen[v] && (graph[v].size() == cornerDegree || graph[v].size() == cornerDegree + 1)) {51 row.add(v);52 seen[v] = true;53 break;54 }55 }56 return row.stream().mapToInt(Integer::intValue).toArray();57 }58}59