SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

34083 0 0 JavaScript
2021-01-06 17:13:52 -03:00
// https://en.wikipedia.org/wiki/Neighbourhood_(graph_theory)
2021-01-06 17:37:19 -03:00
class Graph {
2021-01-06 17:10:09 -03:00
// Generic graph: the algorithm works regardless of direction or weight
constructor() {
2021-01-06 17:10:09 -03:00
this.edges = []
}
addEdge(node1, node2) {
2021-01-06 17:10:09 -03:00
// Adding edges to the graph
this.edges.push({
node1,
node2
})
}
nodeNeighbors(node) {
2021-01-06 17:10:09 -03:00
// Returns an array with all of the node neighbors
const neighbors = new Set()
2021-01-18 20:56:58 -03:00
for (const edge of this.edges) {
2021-01-06 17:10:09 -03:00
// Checks if they have an edge between them and if the neighbor is not
// already in the neighbors array
if (edge.node1 === node && !neighbors.has(edge.node2)) {
2021-01-18 20:54:44 -03:00
neighbors.add(edge.node2)
} else if (edge.node2 === node && !neighbors.has(edge.node1)) {
2021-01-18 20:54:44 -03:00
neighbors.add(edge.node1)
2021-01-06 17:10:09 -03:00
}
}
return neighbors
}
}
export { Graph }
// const graph = new Graph()
// graph.addEdge(1, 2)
// graph.addEdge(2, 3)
// graph.addEdge(3, 5)
// graph.addEdge(1, 5)
// graph.nodeNeighbors(1)