We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 473af78 commit 794d9d2Copy full SHA for 794d9d2
Data-Structure/Graph/countTrees.js
@@ -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());
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments