본문 바로가기

CS

[자료구조] Graph - JavaScript

// 그래프 정점(Vertex) 클래스 정의
class Vertex {
    constructor(value) {
        this.value = value;
        this.edges = new Map(); // Map을 사용하여 이웃 노드 저장
    }

    addEdge(vertex, weight) {
        this.edges.set(vertex, weight); // 이웃 노드와 가중치를 Map에 저장
    }

    removeEdge(vertex) {
        this.edges.delete(vertex); // Map에서 이웃 노드 제거
    }
}

// 그래프(Graph) 클래스 정의
class Graph {
    constructor() {
        this.vertices = new Map(); // Map을 사용하여 정점 저장
    }

    addVertex(value) {
        const vertex = new Vertex(value);
        this.vertices.set(value, vertex); // 정점을 Map에 저장
        return vertex;
    }

    removeVertex(value) {
        const vertexToRemove = this.vertices.get(value);
        if (vertexToRemove) {
            // 정점의 이웃 노드들을 먼저 제거
            vertexToRemove.edges.forEach((_, neighbor) => {
                neighbor.removeEdge(vertexToRemove);
            });
            this.vertices.delete(value); // 정점을 Map에서 제거
        }
    }

    addEdge(vertex1Value, vertex2Value, weight = 1) {
        const vertex1 = this.vertices.get(vertex1Value);
        const vertex2 = this.vertices.get(vertex2Value);
        if (vertex1 && vertex2) {
            vertex1.addEdge(vertex2, weight);
            vertex2.addEdge(vertex1, weight);
        }
    }

    removeEdge(vertex1Value, vertex2Value) {
        const vertex1 = this.vertices.get(vertex1Value);
        const vertex2 = this.vertices.get(vertex2Value);
        if (vertex1 && vertex2) {
            vertex1.removeEdge(vertex2);
            vertex2.removeEdge(vertex1);
        }
    }
}

// 그래프 생성 및 사용 예시
const myGraph = new Graph();

const vertexA = myGraph.addVertex('A');
const vertexB = myGraph.addVertex('B');
const vertexC = myGraph.addVertex('C');

myGraph.addEdge('A', 'B');
myGraph.addEdge('B', 'C');

console.log([...myGraph.vertices.values()]);
// 출력: [
//   Vertex { value: 'A', edges: Map { 'B' => 1 } },
//   Vertex { value: 'B', edges: Map { 'A' => 1, 'C' => 1 } },
//   Vertex { value: 'C', edges: Map { 'B' => 1 } }
// ]

'CS' 카테고리의 다른 글

깊이 우선 탐색 (Depth-First Search, DFS)  (0) 2023.09.15
[자료구조] Graph  (0) 2023.09.14
[자료구조] Trie  (0) 2023.09.09
[자료구조] Queue  (0) 2023.08.31
[자료구조] Stack - 1  (0) 2023.08.30