Skip to content

Commit 76754bc

Browse files
committed
update dfs: include printing connected components information
1 parent bffc42b commit 76754bc

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

Data Structures/Graph/graph.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,21 +93,34 @@ console.log("BFS shortest path: ", bfs(0, 12));
9393

9494
function dfs(s) {
9595
let visited = new Array(graph.vertices).fill(false);
96+
let prev = new Array(graph.vertices).fill(null);
9697

9798
let visit = (at) => {
98-
if (visited[at]) return;
99+
// if (visited[at]) return;
99100
console.log("visit node: ", at);
100101
visited[at] = true;
101102

102103
let neighbors = graph.edges[at];
103104
let curr = neighbors.head;
104105
while (curr) {
105-
visit(curr.data);
106+
prev[curr.data] = at;
107+
if (!visited[curr.data]) {
108+
visit(curr.data);
109+
}
106110
curr = curr.next;
107111
}
108112
};
109113

110-
return visit(s);
114+
visit(s);
115+
116+
// let path = [];
117+
// for (let i = 0; i !== null; i = prev[i]) {
118+
// path.push(i);
119+
// }
120+
121+
// console.log("path: ", path.reverse());
122+
123+
return prev;
111124
}
112125

113126
console.log("DFS from 0: ", dfs(0));
@@ -140,8 +153,8 @@ function findComponents() {
140153

141154
for (let i = 0; i < newGraph.vertices; i++) {
142155
if (!visited[i]) {
143-
visit(i);
144156
count++;
157+
visit(i);
145158
}
146159
}
147160

@@ -159,6 +172,17 @@ function findComponents() {
159172
}
160173
}
161174

175+
let map = new Map();
176+
for (let i = 0; i < components.length; i++) {
177+
if (map.has(`Connected component ${components[i]}`)) {
178+
map.get(`Connected component ${components[i]}`).push(i);
179+
} else {
180+
map.set(`Connected component ${components[i]}`, [i]);
181+
}
182+
}
183+
184+
console.log("Connected Components: ", map);
185+
162186
return {
163187
count: count,
164188
components: components,

0 commit comments

Comments
 (0)