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 504b77e

Browse files
Merge pull request #21 from knockcat/patch-2
Create Connected_component_DFS.cpp
2 parents a167d47 + 4bd4be0 commit 504b77e

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

‎Graphs1/Connected_component_DFS.cpp‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Return All Connected Connected_Components
2+
3+
#include <iostream>
4+
#include <vector>
5+
#include <algorithm>
6+
using namespace std;
7+
8+
void DFS(int **edges, bool *visited, int n, vector<int> &ans, int start)
9+
{
10+
visited[start] = true;
11+
ans.push_back(start);
12+
13+
for (int i = 0; i < n; ++i)
14+
{
15+
if (edges[start][i] == 1 && !visited[i])
16+
DFS(edges, visited, n, ans, i);
17+
}
18+
}
19+
20+
void Connected_Components(int **edges, int n)
21+
{
22+
bool *visited = new bool[n];
23+
24+
for (int i = 0; i < n; ++i)
25+
visited[i] = false;
26+
27+
for (int i = 0; i < n; ++i)
28+
{
29+
if (!visited[i])
30+
{
31+
// this vector creating againg and again
32+
vector<int> ans;
33+
34+
DFS(edges, visited, n, ans, i);
35+
sort(ans.begin(), ans.end());
36+
37+
for (int j = 0; j < ans.size(); ++j)
38+
{
39+
cout << ans[j] << " ";
40+
}
41+
cout << endl;
42+
}
43+
}
44+
delete[] visited;
45+
}
46+
47+
int main()
48+
{
49+
50+
// KNOCKCAT \\
51+
52+
int n;
53+
int e;
54+
55+
cout << "Enter number of vertices & edges : " << endl;
56+
cin >> n >> e;
57+
58+
// for storing we need to create a 2 d array n * n
59+
60+
int **edges = new int *[n]; // dynamic array for storing edges
61+
62+
for (int i = 0; i < n; ++i)
63+
{
64+
edges[i] = new int[n];
65+
for (int j = 0; j < n; ++j)
66+
{
67+
edges[i][j] = 0;
68+
}
69+
}
70+
71+
for (int i = 0; i < e; ++i) // e edges
72+
{
73+
int f, s; // first vertex second vertex
74+
cout << "Enter edge from first vertex to second vertex " << endl;
75+
76+
cin >> f >> s;
77+
edges[f][s] = 1;
78+
edges[s][f] = 1;
79+
}
80+
81+
cout << "Connected Components are " << endl;
82+
Connected_Components(edges, n);
83+
84+
// deleting all the memory
85+
86+
for (int i = 0; i < n; ++i)
87+
delete[] edges[i];
88+
89+
delete[] edges;
90+
91+
return 0;
92+
}

0 commit comments

Comments
(0)

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