-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path연결된정점들.js
80 lines (70 loc) · 1.76 KB
/
연결된정점들.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class makeList{
constructor(){
this.vertices = {};
}
addVertex(vertex) {
if(!this.vertices[vertex]){
this.vertices[vertex] = [];
}
}
contains(vertex) {
return !!this.vertices[vertex];
}
addEdge(fromVertex, toVertex) {
if (!this.contains(fromVertex) || !this.contains(toVertex)) {
return;
}
if (!this.hasEdge(fromVertex, toVertex)) {
this.vertices[fromVertex].push(toVertex);
}
if (!this.hasEdge(toVertex, fromVertex)) {
this.vertices[toVertex].push(fromVertex);
}
}
hasEdge(fromVertex, toVertex) {
if (!this.contains(fromVertex)) {
return false;
}
return !!this.vertices[fromVertex].includes(toVertex);
}
}
function dfs(nodeList,adjList){
const visited = {};
let count =0;
Object.keys(nodeList).forEach((node)=>{
if(!visited[node]){
let q=[];
q.push(node);
while(q.length>0){
const popNode = q.pop();
visited[popNode] = true;
adjList.vertices[popNode].map((ele)=>{
if(!visited[ele]){
q.push(ele);
}
})
}
count++;
}
})
return count;
}
function connectedVertices(edges) {
const adjList = new makeList();
const nodeList = {};
edges.forEach((edge)=>{
const [from,to] = edge;
if(!nodeList[from]) nodeList[from] = true;
if(!nodeList[to]) nodeList[to] = true;
adjList.addVertex(from);
adjList.addVertex(to);
adjList.addEdge(from,to);
})
return dfs(nodeList,adjList);
}
const result = connectedVertices([
[0, 1],
[2, 3],
[4, 5],
]);
console.log(result);