File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
C++/Data-Structures/Graph Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+ #define N 100000
5+
6+ vector<int > gr1[N], gr2[N];
7+
8+ bool vis1[N], vis2[N];
9+
10+ // Function to add edges
11+ void Add_edge (int u, int v)
12+ {
13+ gr1[u].push_back (v);
14+ gr2[v].push_back (u);
15+ }
16+
17+ // DFS function
18+ void dfs1 (int x)
19+ {
20+ vis1[x] = true ;
21+
22+ for (auto i : gr1[x])
23+ if (!vis1[i])
24+ dfs1 (i);
25+ }
26+
27+ // DFS function
28+ void dfs2 (int x)
29+ {
30+ vis2[x] = true ;
31+
32+ for (auto i : gr2[x])
33+ if (!vis2[i])
34+ dfs2 (i);
35+ }
36+
37+ bool Is_Connected (int n)
38+ {
39+ // Call for correct direction
40+ memset (vis1, false , sizeof vis1);
41+ dfs1 (1 );
42+
43+ // Call for reverse direction
44+ memset (vis2, false , sizeof vis2);
45+ dfs2 (1 );
46+
47+ for (int i = 1 ; i <= n; i++) {
48+
49+ // If any vertex it not visited in any direction
50+ // Then graph is not connected
51+ if (!vis1[i] and !vis2[i])
52+ return false ;
53+ }
54+
55+ // If graph is connected
56+ return true ;
57+ }
58+
59+
60+ int main ()
61+ {
62+ int n = 4 ;
63+
64+ // Add edges
65+ Add_edge (1 , 2 );
66+ Add_edge (1 , 3 );
67+ Add_edge (2 , 3 );
68+ Add_edge (3 , 4 );
69+
70+ // Function call
71+ if (Is_Connected (n))
72+ cout << " Yes" ;
73+ else
74+ cout << " No" ;
75+
76+ return 0 ;
77+ }
You can’t perform that action at this time.
0 commit comments