TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
depth_first_search.cpp
Go to the documentation of this file.
1
35#include <algorithm>
36#include <iostream>
37#include <vector>
38
45namespace graph {
56void addEdge(std::vector<std::vector<size_t>> *adj, size_t u, size_t v) {
57 /*
58 *
59 * Here we are considering undirected graph that's the
60 * reason we are adding v to the adjacency list representation of u
61 * and also adding u to the adjacency list representation of v
62 *
63 */
64 (*adj)[u - 1].push_back(v - 1);
65 (*adj)[v - 1].push_back(u - 1);
66}
67
80void explore(const std::vector<std::vector<size_t>> &adj, size_t v,
81 std::vector<bool> *visited) {
82 std::cout << v + 1 << " ";
83 (*visited)[v] = true;
84 for (auto x : adj[v]) {
85 if (!(*visited)[x]) {
86 explore(adj, x, visited);
87 }
88 }
89}
90
99void depth_first_search(const std::vector<std::vector<size_t>> &adj,
100 size_t start) {
101 size_t vertices = adj.size();
102
103 std::vector<bool> visited(vertices, false);
104 explore(adj, start, &visited);
105}
106} // namespace graph
107
109int main() {
110 size_t vertices = 0, edges = 0;
111 std::cout << "Enter the Vertices : ";
112 std::cin >> vertices;
113 std::cout << "Enter the Edges : ";
114 std::cin >> edges;
115
117 std::vector<std::vector<size_t>> adj(vertices, std::vector<size_t>());
118
120 std::cout << "Enter the vertices which have edges between them : "
121 << std::endl;
122 while (edges--) {
123 size_t u = 0, v = 0;
124 std::cin >> u >> v;
125 graph::addEdge(&adj, u, v);
126 }
127
129 graph::depth_first_search(adj, 2);
130
131 std::cout << std::endl;
132 return 0;
133}
int main()
Functions for Depth First Search algorithm.
Graph Algorithms.
void explore(const std::vector< std::vector< int > > *adj, int u, std::vector< bool > *visited)
Utility function for depth first seach algorithm this function explores the vertex which is passed in...
void addEdge(std::vector< std::vector< int > > *adj, int u, int v)
Function that add edge between two nodes or vertices of graph.