Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0eeab82

Browse files
committed
find all paths from source to destination in the graph
1 parent 794d9d2 commit 0eeab82

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎Data-Structure/Graph/allPaths.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
class Graph {
3+
constructor(vertex) {
4+
this.listArray = new Array(vertex + 1);
5+
this.visitedArr = new Array(vertex + 1);
6+
for (let index = 0; index <= vertex; index++) {
7+
this.listArray[index] = [];
8+
this.visitedArr[index] = 0;
9+
}
10+
}
11+
addEdge(v, u) {
12+
this.listArray[v].push(u);
13+
}
14+
15+
printAllPaths(source, dest, pathList) {
16+
this.visitedArr[source] = 1;
17+
if (source == dest) {
18+
console.log(pathList);
19+
this.visitedArr[source] = 0;
20+
return;
21+
}
22+
let list = this.listArray[source];
23+
for (let index = 0; index < list.length; index++) {
24+
if (!this.visitedArr[list[index]]) {
25+
pathList.push(list[index]);
26+
this.printAllPaths(list[index], dest, pathList);
27+
pathList.pop();
28+
}
29+
}
30+
this.visitedArr[source] = 0;
31+
}
32+
33+
}
34+
35+
let g1 = new Graph(4);
36+
g1.addEdge(0, 1);
37+
g1.addEdge(0, 2);
38+
g1.addEdge(0, 3);
39+
40+
g1.addEdge(1, 3);
41+
42+
g1.addEdge(2, 0);
43+
g1.addEdge(2, 1);
44+
45+
let source = 2, dest = 3;
46+
let pathList = [];
47+
pathList.push(source);
48+
g1.printAllPaths(source, dest, pathList)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /