Skip to content

Commit 46c211f

Browse files
committed
check graph is connected or not
1 parent 21f6c3c commit 46c211f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict';
2+
let arrayList1 = null,
3+
arrayList2 = null;
4+
let visitedList1 = [], visitedList2 = [];
5+
function addEdge(u, v) {
6+
arrayList1[u].push(v);
7+
arrayList2[v].push(u);
8+
}
9+
function dfs1(vertex) {
10+
visitedList1[vertex] = true;
11+
for (const item of arrayList1[vertex]) {
12+
if (!visitedList1[item]) dfs1(item);
13+
}
14+
}
15+
16+
function dfs2(vertex) {
17+
visitedList2[vertex] = true;
18+
for (const item of arrayList2[vertex]) {
19+
if (!visitedList2[item]) dfs2(item);
20+
}
21+
}
22+
23+
function checkGraphConnectedOrNot(n) {
24+
arrayList1 = new Array(n + 1);
25+
arrayList2 = new Array(n + 1);
26+
for (let index = 1; index <= n; index++) {
27+
arrayList1[index] = [];
28+
arrayList2[index] = [];
29+
visitedList1[index] = false;
30+
visitedList2[index] = false;
31+
}
32+
addEdge(1, 2);
33+
addEdge(1, 3);
34+
addEdge(2, 3);
35+
addEdge(3, 4);
36+
dfs1(1);
37+
dfs2(1);
38+
for (let index = 1; index <= n; index++) {
39+
if (visitedList1[index] == false && visitedList2[index] == false) return false;
40+
}
41+
return true;
42+
}
43+
let n = 4;
44+
console.log('Graph is connected ? ', checkGraphConnectedOrNot(n));

0 commit comments

Comments
 (0)