Depth First Search

About

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 2; bool vis[N]; vector<int> adj[N]; void dfs(int node) { vis[node] = true; cout << node << " "; vector<int>::iterator it; for (it = adj[node].begin(); it != adj[node].end(); it++) { if (!vis[*it]) { dfs(*it); } } } int main() { memset(vis, false, sizeof(vis)); int n, m; cin >> n >> m; int x, y; for (int i = 0; i < m; i++) { cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } dfs(1); return 0; }

The Depth-first search(DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. Extra memory, usually a stack, is needed to keep track of the nodes discovered so far along a specified branch which helps in backtracking of the graph.

Approach

A standard DFS implementation puts each vertex of the graph into one of two categories:
  • Visited
  • Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles. The DFS algorithm works as follows:
  1. Start by putting any one of the graph's vertices on top of a stack.
  2. Take the top item of the stack and add it to the visited list.
  3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the stack.
  4. Keep repeating steps 2 and 3 until the stack is empty.

Time Complexity

  • Worst Case Time Complexity is: O(V + E)
  • Average Case Time Complexity is: O(V + E)
  • Best Case Time Complexity is: Ω(1)