From ed5df52ae7b969ebb04f5148f5e4b28ce7a63702 Mon Sep 17 00:00:00 2001 From: Krishna Gupta Date: Thu, 30 Oct 2025 20:11:24 +0530 Subject: [PATCH] Add DFS --- DSA/dfs.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 DSA/dfs.cpp diff --git a/DSA/dfs.cpp b/DSA/dfs.cpp new file mode 100644 index 0000000..d256b50 --- /dev/null +++ b/DSA/dfs.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; + +vector> buildGraph(int n, const vector>& edges, bool directed = false) { + vector> adj(n); + for (auto &e : edges) { + int u = e.first, v = e.second; + adj[u].push_back(v); + if (!directed) adj[v].push_back(u); + } + return adj; +} + +void dfsUtil(int u, const vector> &adj, vector &visited, vector &parent) { + visited[u] = 1; + cout << u << " "; + for (int v : adj[u]) { + if (!visited[v]) { + parent[v] = u; + dfsUtil(v, adj, visited, parent); + } + } +} + +void dfs(const vector> &adj) { + int n = adj.size(); + vector visited(n, 0), parent(n, -1); + int components = 0; + + for (int i = 0; i < n; ++i) { + if (!visited[i]) { + components++; + cout << "Component " << components << ": "; + dfsUtil(i, adj, visited, parent); + cout << "\n"; + } + } +} + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int n, m; + cin >> n >> m; + vector> edges; + for (int i = 0; i < m; ++i) { + int u, v; + cin >> u >> v; + // --u; --v; // uncomment if input is 1-indexed + edges.emplace_back(u, v); + } + + vector> adj = buildGraph(n, edges, false); + cout << "DFS Traversal:\n"; + dfs(adj); + + return 0; +} \ No newline at end of file