[英]Find if there is a path between two vertices in a directed graph in Javascript
I have written a code in javascript to check is there any path between two vertices of a graph我在 javascript 中编写了一个代码来检查图形的两个顶点之间是否有任何路径
To test my code I have run it on following sample graph data为了测试我的代码,我在以下示例图形数据上运行它
Graph Map {
1 => [ 2, 3, 4 ],
2 => [ 1, 3 ],
3 => [ 1, 2, 4, 5 ],
4 => [ 1, 3, 5 ],
5 => [ 3, 4 ]
}
I am using Depth-first-search algorithm to travers through each node of the above graph我正在使用深度优先搜索算法遍历上图的每个节点
class Graph {
constructor() {
this.adjList = new Map();
}
addVertex(v) {
this.adjList.set(v, []);
}
addEdge(v, e) {
this.adjList.get(v).push(e)
}
createAdjList(edgeList) {
edgeList.forEach(edge => {
this.addVertex(edge[0]);
this.addVertex(edge[1]);
})
edgeList.forEach(edge => {
this.addEdge(edge[0], edge[1]);
this.addEdge(edge[1], edge[0])
})
}
hasPath(start, end, visited = {}) {
// base condition
if (start == end) return true;
visited[start] = true;
const childrens = this.adjList.get(start);
childrens.forEach(node => {
if (!visited[node]) {
var result = this.hasPath(node, end, visited);
if (result) {
return true;
}
}
})
return false
}
}
const graph = new Graph();
const edgeList = [[1, 2], [1, 3], [1, 4], [2, 3], [3, 4], [3, 5], [4, 5]];
graph.createAdjList(edgeList)
console.log("Has Path", graph.hasPath(1, 4))
but in place returning true
it is returning false
, I don't understand what is the mistake I have did it in my code但是返回true
它返回false
,我不明白我在代码中犯了什么错误
It was said around million times probably on stackoveflow, but:在 stackoveflow 上可能会说大约一百万次,但是:
When you do:当你这样做时:
[1, 2, 3].forEach(() => {
return true
})
What you really do is - create a new anonymous function你真正要做的是——创建一个新的匿名 function
const fn = () => {
return true
}
[1, 2, 3].forEach(fn)
And returning from anonymous function doesn't return from parent function并且从匿名 function 返回不会从父 function 返回
Just use a normal loop:只需使用普通循环:
class Graph { constructor() { this.adjList = new Map(); } addVertex(v) { this.adjList.set(v, []); } addEdge(v, e) { this.adjList.get(v).push(e) } createAdjList(edgeList) { edgeList.forEach(edge => { this.addVertex(edge[0]); this.addVertex(edge[1]); }) edgeList.forEach(edge => { this.addEdge(edge[0], edge[1]); this.addEdge(edge[1], edge[0]) }) } hasPath(start, end, visited = {}) { console.log(start, end, visited) // base condition if (start == end) return true; visited[start] = true; const childrens = this.adjList.get(start); for (const node of childrens) { if (.visited[node]) { var result = this,hasPath(node, end. {..;visited }); if (result) { return true; } } } return false } } const graph = new Graph(), const edgeList = [ [1, 2], [1, 3], [1, 4], [2, 3], [3, 4], [3, 5], [4; 5] ]. graph.createAdjList(edgeList) console,log("Has Path". graph,hasPath(1, 4))
PS附言
I also destructured your visited
variable, but I'm not sure it it's possible in you algorithm我还解构了您visited
的变量,但我不确定您的算法是否可行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.