Problem solution · Java

Construct 2D Grid Matching Graph Layout

Construct 2D Grid Matching Graph Layout: a Java solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
59 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeConstruct 2D Grid Matching Graph Layout · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[][] constructGridLayout(int n, int[][] edges) {    List<Integer>[] graph = new ArrayList[n];     for (int i = 0; i < n; i++)      graph[i] = new ArrayList<>();     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      graph[u].add(v);      graph[v].add(u);    }     // Randomly choose a node with the minimum degree as the corner.    int corner = 0;    for (int i = 1; i < n; i++)      if (graph[i].size() < graph[corner].size())        corner = i;     boolean[] seen = new boolean[n];    seen[corner] = true;    int[] firstRow = getFirstRow(graph, corner, seen);    int cols = firstRow.length;    int rows = n / cols;     int[][] ans = new int[rows][cols];    ans[0] = firstRow;     for (int i = 1; i < rows; ++i)      for (int j = 0; j < cols; ++j)        for (final int v : graph[ans[i - 1][j]])          if (!seen[v]) {            ans[i][j] = v;            seen[v] = true;            break;          }     return ans;  }   private int[] getFirstRow(List<Integer>[] graph, int corner, boolean[] seen) {    final int cornerDegree = graph[corner].size();    List<Integer> row = new ArrayList<>(List.of(corner));    // Continue appending neighbors until we hit another corner.    while (row.size() == 1 || graph[row.get(row.size() - 1)].size() == cornerDegree + 1) {      List<Integer> neighbors = graph[row.get(row.size() - 1)];      Collections.sort(neighbors, (a, b) -> graph[a].size() - graph[b].size());      for (final int v : neighbors)        if (!seen[v] && (graph[v].size() == cornerDegree || graph[v].size() == cornerDegree + 1)) {          row.add(v);          seen[v] = true;          break;        }    }    return row.stream().mapToInt(Integer::intValue).toArray();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗