This commit is contained in:
Amir Hosseini 2024-07-17 10:42:07 +09:00 committed by GitHub
commit 31ef6a4e65
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 35 additions and 1 deletions

View File

@ -138,6 +138,7 @@ export default class Graph {
*/ */
reverse() { reverse() {
/** @param {GraphEdge} edge */ /** @param {GraphEdge} edge */
const reversedEdges = [];
this.getAllEdges().forEach((edge) => { this.getAllEdges().forEach((edge) => {
// Delete straight edge from graph and from vertices. // Delete straight edge from graph and from vertices.
this.deleteEdge(edge); this.deleteEdge(edge);
@ -145,7 +146,11 @@ export default class Graph {
// Reverse the edge. // Reverse the edge.
edge.reverse(); edge.reverse();
// Add reversed edge back to the graph and its vertices. // Add reversed edge to the list of reversed edges.
reversedEdges.push(edge);
});
reversedEdges.forEach((edge) => {
// Add reversed edge to the graph.
this.addEdge(edge); this.addEdge(edge);
}); });

View File

@ -305,6 +305,35 @@ describe('Graph', () => {
expect(graph.getNeighbors(vertexD)[0].getKey()).toBe(vertexC.getKey()); expect(graph.getNeighbors(vertexD)[0].getKey()).toBe(vertexC.getKey());
}); });
it('should be possible to reverse directed graph with cycle of lenght two', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBA = new GraphEdge(vertexB, vertexA);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBA);
expect(graph.toString()).toBe('A,B');
expect(graph.getAllEdges().length).toBe(2);
expect(graph.getNeighbors(vertexA).length).toBe(1);
expect(graph.getNeighbors(vertexA)[0].getKey()).toBe(vertexB.getKey());
expect(graph.getNeighbors(vertexB).length).toBe(1);
expect(graph.getNeighbors(vertexB)[0].getKey()).toBe(vertexA.getKey());
graph.reverse();
expect(graph.toString()).toBe('A,B');
expect(graph.getAllEdges().length).toBe(2);
expect(graph.getNeighbors(vertexA).length).toBe(1);
expect(graph.getNeighbors(vertexA)[0].getKey()).toBe(vertexB.getKey());
expect(graph.getNeighbors(vertexB).length).toBe(1);
expect(graph.getNeighbors(vertexB)[0].getKey()).toBe(vertexA.getKey());
});
it('should return vertices indices', () => { it('should return vertices indices', () => {
const vertexA = new GraphVertex('A'); const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B'); const vertexB = new GraphVertex('B');