|
| 1 | +- ๋ฌธ์ |
| 2 | + - ์ ๋ฃ: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ |
| 3 | + - ๋ฌด๋ฃ: https://neetcode.io/problems/count-connected-components |
| 4 | +- ํ์ด: https://algorithm.jonghoonpark.com/2024/07/03/leetcode-323 |
| 5 | + |
| 6 | +```java |
| 7 | +public class Solution { |
| 8 | + public int countComponents(int n, int[][] edges) { |
| 9 | + Map<Integer, Vertex> vertexMap = new HashMap<>(); |
| 10 | + int lastGroupId = 0; |
| 11 | + |
| 12 | + for (int[] edge : edges) { |
| 13 | + Vertex v1 = vertexMap.getOrDefault(edge[0], new Vertex(edge[0])); |
| 14 | + Vertex v2 = vertexMap.getOrDefault(edge[1], new Vertex(edge[1])); |
| 15 | + |
| 16 | + v1.edges.add(v2); |
| 17 | + v2.edges.add(v1); |
| 18 | + |
| 19 | + vertexMap.put(edge[0], v1); |
| 20 | + vertexMap.put(edge[1], v2); |
| 21 | + } |
| 22 | + |
| 23 | + for (int i = 0; i < n; i++) { |
| 24 | + Vertex vertex = vertexMap.get(i); |
| 25 | + if (vertex == null) { |
| 26 | + lastGroupId++; |
| 27 | + } else { |
| 28 | + // 0 ์ด ์๋ ๊ฒฝ์ฐ๋ ์ด๋ฏธ ํ์ํ ์ผ์ด์ค๋ฏ๋ก ์คํต |
| 29 | + if (vertex.groupId == 0) { |
| 30 | + lastGroupId++; |
| 31 | + dfs(vertex, lastGroupId); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return lastGroupId; |
| 37 | + } |
| 38 | + |
| 39 | + public void dfs(Vertex vertex, int groupId) { |
| 40 | + vertex.groupId = groupId; |
| 41 | + for (Vertex connected : vertex.edges) { |
| 42 | + if (connected.groupId == 0) { |
| 43 | + dfs(connected, groupId); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +class Vertex { |
| 50 | + int id; |
| 51 | + int groupId; |
| 52 | + List<Vertex> edges; |
| 53 | + |
| 54 | + public Vertex(int id) { |
| 55 | + this.id = id; |
| 56 | + this.edges = new ArrayList<>(); |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +### TC, SC |
| 62 | + |
| 63 | +Vertex ์ ์๋ฅผ V, Edge ์ ์๋ฅผ E ๋ผ๊ณ ํ์์ ๋, |
| 64 | +์๊ฐ ๋ณต์ก๋๋ O(V + E), ๊ณต๊ฐ ๋ณต์ก๋๋ O(V + E) ์ด๋ค. |
0 commit comments