// sizeVertex() : vertex 개수 반환
Graph.prototype.sizeVertex = function () {
return Object.keys(this.edge).length
};
// sizeEdge() : edge 개수 반환
Graph.prototype.sizeEdge = function (vertex) {
return this.edge[vertex] ? Object.keys(this.edge[vertex]).length : 0
};
// print() : 현재 graph 연결 상태 출력
Graph.prototype.print = function (vertex) {
for (let vertex in this.edge){
let neighbors = this.edge[vertex]
if (neighbors.length ==0) continue
process.stdout.write(`${vertex} -> `)
for (let i = 0; i<neighbors.length; i++){
process.stdout.write(`${neighbors[i]} `)
}
console.log("")
}
};
let graph = new Graph();
let vertices = ["A", "B", "C", "D", "E"];
for (let i = 0; i < vertices.length; i++) {
graph.addVertex(vertices[i]);
}
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("A", "D");
graph.addEdge("B", "E");
graph.addEdge("B", "F");
graph.addEdge("C", "G");
graph.addEdge("D", "G");
graph.addEdge("D", "H");
graph.addEdge("E", "I");
graph.print()
// A -> B C D
// B -> E F
// C -> G
// D -> G H
// E -> I
graph.removeEdge("B", "E");
graph.print()
// A -> B C D
// B -> F
// C -> G
// D -> G H
// E -> I
graph.removeEdge("B", "F");
graph.print()
// A -> B C D
// C -> G
// D -> G H
// E -> I
console.log(graph.sizeVertex()) //4
console.log(graph.sizeEdge("C")) //1
console.log(graph.sizeEdge("B")) //0
방향그래프 > 무방향그래프로 바꾸기
// addEdge() : 간선(edge) 추가
Graph.prototype.addEdge = function (v1, v2) {
this.edge[v1].push(v2);
this.edge[v2].push(v1);
};
// removeEdge() : 간선(edge) 삭제
Graph.prototype.removeEdge = function (v1, v2) {
// v1 > v2 삭제
if (this.edge[v1]) {
let idx = this.edge[v1].indexOf(v2);
if (idx != -1) {
this.edge[v1].splice(idx, 1);
}
if (this.edge[v1].length === 0) {
delete this.edge[v1];
}
}
// v2 > v1 삭제
if (this.edge[v2]) {
let idx = this.edge[v2].indexOf(v1);
if (idx != -1) {
this.edge[v2].splice(idx, 1);
}
if (this.edge[v2].length === 0) {
delete this.edge[v2];
}
}
};