Given an undirected graph where each edge has a color (edge coloring), and two nodes s and d, count the number of distinct paths from s to d such that all edges in the path have the same color.
Input:
n =6edges =[[0,1,1],[0,2,2],[1,2,3],[1,3,2],[1,4,4],[2,4,3],[3,4,2]]s =1d =4Output: 3Explanation: There are three unicolored paths from 1 to 4:-1→4(color 4)-1→2→4(color 3)-1→3→4(color 2)
classSolution {
publicintcountUnicoloredPaths(List<int[]> edges, int n, int s, int d) {
Map<Integer, List<int[]>> adj =new HashMap<>();
Set<Integer> colors =new HashSet<>();
for (int[] e : edges) {
adj.computeIfAbsent(e[0], k ->new ArrayList<>()).add(newint[]{e[1], e[2]});
adj.computeIfAbsent(e[1], k ->new ArrayList<>()).add(newint[]{e[0], e[2]});
colors.add(e[2]);
}
int ans = 0;
for (int color : colors) {
boolean[] vis =newboolean[n+1];
ans += dfs(adj, s, d, color, vis);
}
return ans;
}
privateintdfs(Map<Integer, List<int[]>> adj, int u, int d, int color, boolean[] vis) {
if (u == d) return 1;
vis[u]=true;
int cnt = 0;
for (int[] pair : adj.getOrDefault(u, new ArrayList<>())) {
int v = pair[0], c = pair[1];
if (!vis[v]&& c == color) cnt += dfs(adj, v, d, color, vis);
}
vis[u]=false;
return cnt;
}
}
classSolution:
defcount_unicolored_paths(self, edges: list[tuple[int,int,int]], n: int, s: int, d: int) -> int:
from collections import defaultdict
adj = defaultdict(list)
colors = set()
for u, v, c in edges:
adj[u].append((v, c))
adj[v].append((u, c))
colors.add(c)
defdfs(u, color, vis):
if u == d:
return1 vis.add(u)
cnt =0for v, c in adj[u]:
if v notin vis and c == color:
cnt += dfs(v, color, vis)
vis.remove(u)
return cnt
ans =0for color in colors:
ans += dfs(s, color, set())
return ans