Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/data-structures/graph/Graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,19 @@ export default class Graph {
*/
reverse() {
/** @param {GraphEdge} edge */
const reversedEdges = [];
this.getAllEdges().forEach((edge) => {
// Delete straight edge from graph and from vertices.
this.deleteEdge(edge);

// Reverse the edge.
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);
});

Expand Down
29 changes: 29 additions & 0 deletions src/data-structures/graph/__test__/Graph.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,35 @@ describe('Graph', () => {
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', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
Expand Down