class Graph {
constructor() {
this.vertices = []
this.edges = {}
}
addVertices(vertex) {
this.vertices.push(vertex)
this.edges[vertex] = []
}
addEdge(vertex1, vertex2) {
this.edges[vertex1].push({ "joinedTo": vertex2 })
this.edges[vertex2].push({ "joinedTo": vertex1 })
}
print() {
for (var vertex of this.vertices) {
for (var joined of this.edges[vertex]) {
console.log(vertex + "-->" + joined.joinedTo)
}
}
}
bfs(startVertex, targetVertex) {
var visited = {}
var queue = []
var targetVertexFound = false
visited[startVertex] = true;
queue.push(startVertex)
while (queue.length > 0) {
var currentVertex = queue.shift()
console.log("Current Vertex", currentVertex)
if (currentVertex == targetVertex) {
return true
} else {
var neighbourVertices = this.edges[currentVertex]
for (var neightborVertex of neighbourVertices) {
if (!visited[neightborVertex.joinedTo]) {
visited[neightborVertex.joinedTo] = true;
queue.push(neightborVertex.joinedTo)
}
}
}
}
return targetVertexFound
}
}
const graph = new Graph();
graph.addVertices('A');
graph.addVertices('B');
graph.addVertices('C');
graph.addVertices('D');
graph.addEdge('A', 'B');
graph.addEdge('B', 'C');
graph.addEdge('C', 'D');
graph.addEdge('D', 'A');
var found = graph.bfs('A', 'B');
console.log("C found", found)
No comments:
Post a Comment