|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: (Leetcode) 323 - Number of Connected Components in an Undirected Graph |
| 4 | +categories: [스터디-알고리즘] |
| 5 | +tags: [자바, java, 리트코드, Leetcode, 알고리즘, tree, node, vertex, edge] |
| 6 | +date: 2024-07-03 12:30:00 +0900 |
| 7 | +toc: true |
| 8 | +--- |
| 9 | + |
| 10 | +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. |
| 11 | + |
| 12 | +[https://neetcode.io/practice](https://neetcode.io/practice) |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +- 문제 |
| 17 | + - 유료: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ |
| 18 | + - 무료: https://neetcode.io/problems/count-connected-components |
| 19 | + |
| 20 | +## 내가 작성한 풀이 |
| 21 | + |
| 22 | +```java |
| 23 | +public class Solution { |
| 24 | + public int countComponents(int n, int[][] edges) { |
| 25 | + Map<Integer, Vertex> vertexMap = new HashMap<>(); |
| 26 | + int lastGroupId = 0; |
| 27 | + |
| 28 | + for (int[] edge : edges) { |
| 29 | + Vertex v1 = vertexMap.getOrDefault(edge[0], new Vertex(edge[0])); |
| 30 | + Vertex v2 = vertexMap.getOrDefault(edge[1], new Vertex(edge[1])); |
| 31 | + |
| 32 | + v1.edges.add(v2); |
| 33 | + v2.edges.add(v1); |
| 34 | + |
| 35 | + vertexMap.put(edge[0], v1); |
| 36 | + vertexMap.put(edge[1], v2); |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < n; i++) { |
| 40 | + Vertex vertex = vertexMap.get(i); |
| 41 | + if (vertex == null) { |
| 42 | + lastGroupId++; |
| 43 | + } else { |
| 44 | + // 0 이 아닐 경우는 이미 탐색한 케이스므로 스킵 |
| 45 | + if (vertex.groupId == 0) { |
| 46 | + lastGroupId++; |
| 47 | + dfs(vertex, lastGroupId); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return lastGroupId; |
| 53 | + } |
| 54 | + |
| 55 | + public void dfs(Vertex vertex, int groupId) { |
| 56 | + vertex.groupId = groupId; |
| 57 | + for (Vertex connected : vertex.edges) { |
| 58 | + if (connected.groupId == 0) { |
| 59 | + dfs(connected, groupId); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +class Vertex { |
| 66 | + int id; |
| 67 | + int groupId; |
| 68 | + List<Vertex> edges; |
| 69 | + |
| 70 | + public Vertex(int id) { |
| 71 | + this.id = id; |
| 72 | + this.edges = new ArrayList<>(); |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +### TC, SC |
| 78 | + |
| 79 | +Vertex 의 수를 V, Edge 의 수를 E 라고 하였을 때, |
| 80 | +시간 복잡도는 O(V + E), 공간 복잡도는 O(V + E) 이다. |
0 commit comments