Approach
Breadth-first search
For Number of Ways to Assign Edge Weights I, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 42 lines of Java from the credited upstream file 3558.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 assignEdgeWeights(int[][] edges) {3 final int n = edges.size() + 1;4 List<Integer>[] graph = new List[n + 1];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] edge : edges) {8 final int u = edge[0];9 final int v = edge[1];10 graph[u].add(v);11 graph[v].add(u);12 }13 14 Queue<Integer> q = new ArrayDeque<>(List.of(1));15 boolean[] seen = new boolean[n + 1];16 seen[1] = true;17 18 int step = 0;19 for (step = 0; !q.isEmpty(); ++step)20 for (int sz = q.size(); sz > 0; --sz) {21 final int u = q.poll();22 for (final int v : graph[u])23 if (!seen[v]) {24 q.offer(v);25 seen[v] = true;26 }27 }28 29 return step > 0 ? modPow(2, step - 2) : 0;30 }31 32 private static final int MOD = 1_000_000_007;33 34 private int modPow(long x, long n) {35 if (n == 0)36 return 1;37 if (n % 2 == 1)38 return (int) (x * modPow(x % MOD, (n - 1)) % MOD);39 return modPow(x * x % MOD, (n / 2)) % MOD;40 }41}42