classSolution: defcountCompleteComponents(self, n: int, edges: List[List[int]]) -> int: g = [[] for _ inrange(n)] for x, y in edges: g[x].append(y) g[y].append(x)
vis = [False] * n defdfs(x: int) -> None: vis[x] = True nonlocal v, e v += 1 e += len(g[x]) for y in g[x]: ifnot vis[y]: dfs(y)
ans = 0 for i, b inenumerate(vis): ifnot b: v = e = 0 dfs(i) ans += e == v * (v - 1) return ans
publicintcountCompleteComponents(int n, int[][] edges) { g = newArrayList[n]; Arrays.setAll(g, e -> newArrayList<>()); for (var e : edges) { intx= e[0], y = e[1]; g[x].add(y); g[y].add(x); // 建图 }
intans=0; vis = newboolean[n]; for (inti=0; i < n; i++) { if (!vis[i]) { v = 0; e = 0; dfs(i); if (e == v * (v - 1)) ans++; } } return ans; }
privatevoiddfs(int x) { vis[x] = true; v++; e += g[x].size(); for (var y : g[x]) if (!vis[y]) dfs(y); } }
funccountCompleteComponents(n int, edges [][]int) (ans int) { g := make([][]int, n) for _, e := range edges { x, y := e[0], e[1] g[x] = append(g[x], y) g[y] = append(g[y], x) } vis := make([]bool, n) var v, e int var dfs func(int) dfs = func(x int) { vis[x] = true v++ e += len(g[x]) for _, y := range g[x] { if !vis[y] { dfs(y) } } } for i, b := range vis { if !b { v, e = 0, 0 dfs(i) if e == v*(v-1) { ans++ } } } return }