Skip to content

Commit eb7476e

Browse files
committedJul 3, 2024
week10 mission number-of-connected-components-in-an-undirected-graph
1 parent 2c9e055 commit eb7476e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
 
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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

Comments
 (0)
Please sign in to comment.