Depth First Search |
A graph traversal algorithm that explores as far as possible along each branch before backtracking. The algorithm starts at a specified source vertex and explores its neighbors recursively, marking each visited vertex as visited to avoid revisiting them.
Time Complexity: O(m+n), where m is the number of edges and n is the number of vertices
vector<bool> visited; int current_time = 0; void DFS(vector<vector<int>> & graph, int vertix) { current_time++; if (visited.empty()) { visited.resize(graph.size(), false); } visited.at(vertix) = true; for (int i = 0; i <graph.at(vertix).size(); i++) { if (!visited.at(graph.at(vertix).at(i))) { DFS(graph, graph.at(vertix).at(i)); } } current_time++; cout << "Finished the Discovery of Vertix (" << vertix << ")"; // Comment the line below if the time of discovery was not important cout << " at time (" << current_time << ")" << endl; }