zrwusa / data-structure-typed

Javascript Data Structure & TypeScript Data Structure. Heap, Binary Tree, Red Black Tree, Linked List, Deque, Trie, HashMap, Directed Graph, Undirected Graph, Binary Search Tree, AVL Tree, Priority Queue, Graph, Queue, Tree Multiset, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue, Stack.
https://data-structure-typed-docs.vercel.app
MIT License
119 stars 9 forks source link

[BUG] deleteVertex deletes all of it's neighbors from the inEdge Map, even when that neighbor still has Vertex's outgoing to it #86

Closed jasonmacdonald closed 7 months ago

jasonmacdonald commented 7 months ago

Describe the bug Mostly what the title says.

Here is a simple reproduction

const graph = new DirectedGraph();
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');

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

// 'Incoming to A should contain ['B','C']
console.log(graph.incomingEdgesOf('A').map((e) => e.src)); //  ['B','C']

// Now delete B, which has no direct link to C, only that C -> A.
graph.deleteVertex('B');

// Now if we do the same call to incoming edges for A we should get only ['C']
console.log(
    graph.incomingEdgesOf('A').map((e) => e.src), // []
);

// but it only shows an empty array, since we deleted all of `A's edges, not just the one to `B`.

// If we check C, it correctly shows A as an outgoing edge, 
// even though A no longer has any knowledge of C linking to it.
console.log(graph.outgoingEdgesOf('C').map((e) => e.dest));

Unless I'm fundamentally misunderstanding how this should work, deleting B should not wipe out all incoming edges to A, only the edges pointing at B.

I tracked the issue here https://github.com/zrwusa/data-structure-typed/blob/main/src/data-structures/graph/directed-graph.ts#L264, which I believe should be deleting an edge inside A's set of edges, not all of A's edges.

jasonmacdonald commented 7 months ago

Changing that line from this._inEdgeMap.delete(neighbor); to this.deleteEdgeSrcToDest(vertex, neighbor); appears to fix the issue.