class UndirectedGraph {
constructor() {
this.edges = {};
}
// 정점 추가하기
addVertex(vertex) {
this.edges[vertex] = {};
}
// 간선 추가하기
addEdge(vertex1, vertex2, weight = 0) {
this.edges[vertex1][vertex2] = weight;
this.edges[vertex2][vertex1] = weight;
}
// 간선 삭제하기
removeEdge(vertex1, vertex2) {
if (this.edges[vertex1] && this.edges[vertex1][vertex2] !== undefined) {
delete this.edges[vertex1][vertex2];
}
if (this.edges[vertex2] && this.edges[vertex2][vertex1] !== undefined) {
delete this.edges[vertex2][vertex1];
}
}
// 정점 삭제하기 (반대편 정점에서도 간선을 삭제해야함)
removeVertex(vertex) {
for (let adjacentVertex in this.edges[vertex]) {
this.removeEdge(adjacentVertex, vertex);
}
delete this.edges[vertex];
}
}
class DirectedGraph {
constructor() {
this.edges = {};
}
// 정점 추가
addVertex(vertex) {
this.edges[vertex] = {};
}
// 간선 추가
addEdge(from, to, weight = 0) {
// 시작 정점, 도착 정점, 가중치
this.edges[from][to] = weight;
}
// 간선 삭제
removeEdge(vertex1, vertex2) {
if (this.edges[vertex1] && this.edges[vertex1][vertex2] !== undefined) {
delete this.edges[vertex1][vertex2];
}
}
// 정점 삭제하기 (반대편 정점에서도 간선을 삭제해야함)
removeVertex(vertex) {
for (let adjacentVertex in this.edges[vertex]) {
this.removeEdge(adjacentVertex, vertex);
}
delete this.edges[vertex];
}
Github | tech-interview-for-developer
Github | Interview_Question_for_Beginner
Github | javascript-algorithms | trekhleb
[자료구조] 그래프 (자바스크립트/javascript)
Photo by Alain Pham on Unsplash