JSFiddle - React, Tailwind, and code Playground
JavaScript
function Graph(v) {
this.vertices = v;
this.edges = 0;
//adjacency list for the vertices.
this.adj = [];
for (var i = 0; i < this.vertices; i++) {
this.adj[i] = [];
}
//marked flag for depthFirst search
this.marked = [];
this.possibleToVisit = [];
for (var i = 0; i < this.vertices; i++) {
this.marked[i] = false;
};
this.addEdge = addEdge;
// this.showGraph = showGraph;
this.dfs = dfs;
this.startDfs = startDfs;
this.checkRoute = checkRoute;
}
function addEdge(from, to) {
this.adj[from].push(to);
this.adj[to].push(from);
this.edges++;
}
function showGraph() {
for (var i = 0; i < this.vertices; ++i) {
console.log(i + " -> ");
// for (var j = 0; j < this.vertices; ++j) {
// if (this.adj[i][j] !== undefined) {
// console.log(this.adj[i][j] + ' ');
// }
// }
// }
// }
function startDfs(v) {
this.possibleToVisit = []; // here, you can reset any values
this.dfs(v);
return true; // here, you can return a custom object containing 'possibleToVisit'
}
function dfs(v) {
this.marked[v] = true;
if (this.adj[v] !== undefined) {
//console.log("visited vertex " + v);
}
for (var i = 0; i < this.adj[v].length; i++) {
var w = this.adj[v][i];
if (!this.marked[w]) {
this.possibleToVisit.push(w)
this.dfs(w);
}
}
// console.log(possibleToVisit);
}
function checkRoute(v, v2){
this.dfs(v);
if(this.possibleToVisit.indexOf(v2) === -1){
return false;
}
return true;
}
g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.showGraph();
g.dfs(0);
console.log(g.checkRoute(0,4));
console.log(g.checkRoute(0,5));
console.log(g.possibleToVisit)