mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Use Infinity instead of zero in Graph adjacency matrix to show that vertices are not connected.
This commit is contained in:
@@ -177,18 +177,17 @@ export default class Graph {
|
||||
const vertices = this.getAllVertices();
|
||||
const verticesIndices = this.getVerticesIndices();
|
||||
|
||||
// Init matrix with zeros.
|
||||
// Init matrix with infinities meaning that there is no ways of
|
||||
// getting from one vertex to another yet.
|
||||
const adjacencyMatrix = Array(vertices.length).fill(null).map(() => {
|
||||
return Array(vertices.length).fill(0);
|
||||
return Array(vertices.length).fill(Infinity);
|
||||
});
|
||||
|
||||
// Fill the columns.
|
||||
vertices.forEach((vertex, vertexIndex) => {
|
||||
vertex.getNeighbors().forEach((neighbor) => {
|
||||
const neighborIndex = verticesIndices[neighbor.getKey()];
|
||||
adjacencyMatrix[vertexIndex][neighborIndex] = this.isDirected ?
|
||||
this.findEdge(vertex, neighbor).weight :
|
||||
1;
|
||||
adjacencyMatrix[vertexIndex][neighborIndex] = this.findEdge(vertex, neighbor).weight;
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -348,10 +348,10 @@ describe('Graph', () => {
|
||||
|
||||
const adjacencyMatrix = graph.getAdjacencyMatrix();
|
||||
expect(adjacencyMatrix).toEqual([
|
||||
[0, 1, 0, 0],
|
||||
[1, 0, 1, 1],
|
||||
[0, 1, 0, 1],
|
||||
[0, 1, 1, 0],
|
||||
[Infinity, 0, Infinity, Infinity],
|
||||
[0, Infinity, 0, 0],
|
||||
[Infinity, 0, Infinity, 0],
|
||||
[Infinity, 0, 0, Infinity],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -375,10 +375,10 @@ describe('Graph', () => {
|
||||
|
||||
const adjacencyMatrix = graph.getAdjacencyMatrix();
|
||||
expect(adjacencyMatrix).toEqual([
|
||||
[0, 2, 0, 0],
|
||||
[0, 0, 1, 7],
|
||||
[0, 0, 0, 5],
|
||||
[0, 0, 0, 0],
|
||||
[Infinity, 2, Infinity, Infinity],
|
||||
[Infinity, Infinity, 1, 7],
|
||||
[Infinity, Infinity, Infinity, 5],
|
||||
[Infinity, Infinity, Infinity, Infinity],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user