From 07cd4018fe1add29c70fca14f9525c47a1b5c18b Mon Sep 17 00:00:00 2001 From: Armunshi <74150159+Armunshi@users.noreply.github.com> Date: Thu, 17 Oct 2024 21:14:52 +0530 Subject: [PATCH] added graph problem of connected components it checks if a given graph is connected or not --- C++/connected-components.cpp | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/connected-components.cpp diff --git a/C++/connected-components.cpp b/C++/connected-components.cpp new file mode 100644 index 0000000..f0fabe3 --- /dev/null +++ b/C++/connected-components.cpp @@ -0,0 +1,46 @@ +#include +#include +using namespace std; +void dfs(vector>& graph, vector& arr, int at) +{ + if (arr[at]) return; + arr[at] = true; + for (int i = 0; i < graph.size(); ++i) { + if (graph[at][i] == 1 && !arr[i]) { + dfs(graph, arr, i); + } + } +} +bool isconn(vector>& graph) { + int n = graph.size(); + vector v(n, false); + int count = 0; + for (int i = 0; i < n; ++i) { + if (!v[i]) { + count += 1; + // if (count > 1) { + // return false; + // } + dfs(graph, v, i); + } + } + return count; +} +int main() { + vector> g1 = { + {0, 1, 0, 0}, + {1, 0, 0, 0}, + {0, 0, 0, 1}, + {0, 0, 1, 0} + }; + vector> g2 = { + {0, 1, 1, 0}, + {1, 0, 1, 1}, + {1, 1, 0, 1}, + {0, 1, 1, 0} + }; + + cout << isconn(g1) << endl; + cout << isconn(g2) << endl; + return 0; +}