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
- 64 lines of C++ from the credited upstream file 3311.cpp.
- The implementation visibly relies on sequence storage.
- 6 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:3 vector<vector<int>> constructGridLayout(int n, vector<vector<int>>& edges) {4 vector<vector<int>> graph(n);5 6 for (const vector<int>& edge : edges) {7 const int u = edge[0];8 const int v = edge[1];9 graph[u].push_back(v);10 graph[v].push_back(u);11 }12 13 14 const int corner =15 ranges::min_element(graph, ranges::less{}, &vector<int>::size) -16 graph.begin();17 18 vector<bool> seen(n);19 seen[corner] = true;20 const vector<int> firstRow = getFirstRow(graph, corner, seen);21 const int cols = firstRow.size();22 const int rows = n / cols;23 24 vector<vector<int>> ans(rows, vector<int>(cols));25 ans[0] = firstRow;26 27 for (int i = 1; i < rows; ++i)28 for (int j = 0; j < cols; ++j)29 for (const int v : graph[ans[i - 1][j]])30 if (!seen[v]) {31 ans[i][j] = v;32 seen[v] = true;33 break;34 }35 36 return ans;37 }38 39 private:40 vector<int> getFirstRow(vector<vector<int>>& graph, int corner,41 vector<bool>& seen) {42 const int cornerDegree = graph[corner].size();43 vector<int> row = {corner};44 45 46 while (row.size() == 1 || graph[row.back()].size() == cornerDegree + 1) {47 48 49 vector<int>& neighbors = graph[row.back()];50 ranges::sort(neighbors, ranges::less{},51 [&graph](int v) { return graph[v].size(); });52 for (const int v : neighbors)53 if (!seen[v] && (graph[v].size() == cornerDegree ||54 graph[v].size() == cornerDegree + 1)) {55 row.push_back(v);56 seen[v] = true;57 break;58 }59 }60 61 return row;62 }63};64