From 9a1b1147aa1301deeb3312ef44a628001360f2ed Mon Sep 17 00:00:00 2001 From: Vidhika002 Date: Thu, 6 Oct 2022 18:49:46 +0530 Subject: [PATCH] DFS added --- .vscode/c_cpp_properties.json | 20 ++++++++++++ DFS.cpp | 58 +++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 DFS.cpp diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..1ee5379 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,20 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "C:\\MinGW\\include" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "compilerPath": "C:/MinGW/bin/cpp.exe", + "cStandard": "c17", + "cppStandard": "c++17", + "intelliSenseMode": "windows-msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/DFS.cpp b/DFS.cpp new file mode 100644 index 0000000..020d904 --- /dev/null +++ b/DFS.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +class Graph { + + void DFSUtil(int v); + +public: + map visited; + map > adj; + void addEdge(int v, int w); + + void DFS(); +}; + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); +} + +void Graph::DFSUtil(int v) +{ + visited[v] = true; + cout << v << " "; + + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i); +} + + +void Graph::DFS() +{ + + for (auto i : adj) + if (visited[i.first] == false) + DFSUtil(i.first); +} + +int main() +{ + + Graph g; + g.addEdge(0, 1); + g.addEdge(0, 9); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(9, 3); + + cout << "Following is Depth First Traversal \n"; + + + g.DFS(); + + return 0; +} \ No newline at end of file