Repository navigation
Expand file tree
/
Copy pathgraphs.js
More file actions
111 lines (83 loc) · 1.86 KB
/
Copy pathgraphs.js
File metadata and controls
111 lines (83 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class Graph {
constructor(noOfVertices) {
this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}
addVertex(v) {
this.AdjList.set(v, []);
}
addEdge(v, w) {
this.AdjList.get(v).push(w);
this.AdjList.get(w).push(v);
}
printGraph() {
var get_keys = this.AdjList.keys();
for (var i of get_keys) {
var get_values = this.AdjList.get(i);
var conc = "";
for (var j of get_values)
conc += j + " ";
console.log(i + " -> " + conc);
}
}
bfs(startingNode)
{
var visited = {};
var q = new Queue();
visited[startingNode] = true;
q.enqueue(startingNode);
while (!q.isEmpty()) {
var getQueueElement = q.dequeue();
console.log(getQueueElement);
var get_List = this.AdjList.get(getQueueElement);
for (var i in get_List) {
var neigh = get_List[i];
if (!visited[neigh]) {
visited[neigh] = true;
q.enqueue(neigh);
}
}
}
}
dfs(startingNode)
{
var visited = {};
this.DFSUtil(startingNode, visited);
}
DFSUtil(vert, visited)
{
visited[vert] = true;
console.log(vert);
var get_neighbours = this.AdjList.get(vert);
for (var i in get_neighbours) {
var get_elem = get_neighbours[i];
if (!visited[get_elem])
this.DFSUtil(get_elem, visited);
}
}
}
// Using the above implemented graph class
var g = new Graph(6);
var vertices = ['A', 'B', 'C', 'D', 'E', 'F'];
// adding vertices
for (var i = 0; i < vertices.length; i++) {
g.addVertex(vertices[i]);
}
// adding edges
g.addEdge('A', 'B');
g.addEdge('A', 'D');
g.addEdge('A', 'E');
g.addEdge('B', 'C');
g.addEdge('D', 'E');
g.addEdge('E', 'F');
g.addEdge('E', 'C');
g.addEdge('C', 'F');
// prints all vertex and
// its adjacency list
// A -> B D E
// B -> A C
// C -> B E F
// D -> A E
// E -> A D F C
// F -> E C
g.printGraph();