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 794d9d2

Browse files
committed
count number of trees in a given forest
1 parent 473af78 commit 794d9d2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎Data-Structure/Graph/countTrees.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
dfs(startVertex) {
16+
this.visitedArr[startVertex] = 1;
17+
let tList = this.listArray[startVertex];
18+
for (let index = 0; index < tList.length; index++) {
19+
if (!this.visitedArr[tList[index]]) this.dfs(tList[index]);
20+
}
21+
}
22+
23+
countTrees() {
24+
let cTrees = 0;
25+
for (let index = 1; index < this.visitedArr.length; index++) {
26+
if (!this.visitedArr[index]) {
27+
this.dfs(index);
28+
cTrees++;
29+
}
30+
}
31+
return cTrees;
32+
}
33+
}
34+
35+
let g1 = new Graph(8);
36+
g1.addEdge(1, 2);
37+
g1.addEdge(1, 3);
38+
39+
g1.addEdge(4, 5);
40+
g1.addEdge(4, 6);
41+
42+
g1.addEdge(7, 8);
43+
console.log('Total Number of trees', g1.countTrees());

0 commit comments

Comments
(0)

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