This commit is contained in:
Ricardo Borges 2024-07-17 10:38:28 +09:00 committed by GitHub
commit 528c567c70
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 85 additions and 0 deletions

View File

@ -188,6 +188,36 @@ export default class Graph {
return adjacencyMatrix; return adjacencyMatrix;
} }
/**
* @returns {*[{}]}
*/
getAdjacencyList() {
const edges = this.getAllEdges();
const adjacencyList = {};
edges.forEach((edge) => {
const { weight } = edge;
const startVertexValue = edge.startVertex.value;
const endVertexValue = edge.endVertex.value;
if (adjacencyList[startVertexValue]) {
adjacencyList[edge.startVertex.value].push({ weight, value: endVertexValue });
} else {
adjacencyList[startVertexValue] = [{ weight, value: endVertexValue }];
}
if (!this.isDirected) {
if (adjacencyList[endVertexValue]) {
adjacencyList[endVertexValue].push({ weight, value: startVertexValue });
} else {
adjacencyList[endVertexValue] = [{ weight, value: startVertexValue }];
}
}
});
return adjacencyList;
}
/** /**
* @return {string} * @return {string}
*/ */

View File

@ -385,4 +385,59 @@ describe('Graph', () => {
[Infinity, Infinity, Infinity, Infinity], [Infinity, Infinity, Infinity, Infinity],
]); ]);
}); });
it('should generate adjacency list for undirected graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 2);
const edgeBC = new GraphEdge(vertexB, vertexC, 1);
const edgeCD = new GraphEdge(vertexC, vertexD, 5);
const edgeBD = new GraphEdge(vertexB, vertexD, 7);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeBD);
const adjacencyList = graph.getAdjacencyList();
expect(adjacencyList).toEqual({
A: [{ value: 'B', weight: 2 }],
B: [{ value: 'A', weight: 2 }, { value: 'C', weight: 1 }, { value: 'D', weight: 7 }],
C: [{ value: 'B', weight: 1 }, { value: 'D', weight: 5 }],
D: [{ value: 'C', weight: 5 }, { value: 'B', weight: 7 }],
});
});
it('should generate adjacency list for directed graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 2);
const edgeBC = new GraphEdge(vertexB, vertexC, 1);
const edgeCD = new GraphEdge(vertexC, vertexD, 5);
const edgeBD = new GraphEdge(vertexB, vertexD, 7);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeBD);
const adjacencyList = graph.getAdjacencyList();
expect(adjacencyList).toEqual({
A: [{ value: 'B', weight: 2 }],
B: [{ value: 'C', weight: 1 }, { value: 'D', weight: 7 }],
C: [{ value: 'D', weight: 5 }],
});
});
}); });