Skip to content

Instantly share code, notes, and snippets.

@rahularity
Created July 24, 2020 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahularity/178df66c54a6d4da9da620febc26b149 to your computer and use it in GitHub Desktop.
Save rahularity/178df66c54a6d4da9da620febc26b149 to your computer and use it in GitHub Desktop.
Midnight Code: Day 3

Depth First Search

Used to traverse a tree or a graph in depth first manner

// globally we have a Graph G of lets say 100 nodes
vector<int>* G = new vector<int>[100];
// globally we also have a vector to store weather or not a node has been visited
vector<bool> visited(100, false);


void DFS( int node ){
  // mark the current node as visited
  visited[node] = true;
  
  // for all the adjacent nodes of the current node
  for( int adj : G[node] ){
    // if the adjacent node is not already visited then visit it
    if( !visited[adj] )
      DFS( adj );
  } 
}

Fully Working Code Here

Applications:

  • Traversal of Graph, explore Nodes and Edges of a Graph. code

  • Used as a building block in other Algorithms:

    • Count Connected Components
    • Determine Connectivity
    • Find Bridges and Articulation Points in a Graph
  • For a unweighted graph DFS traversal produces

    • Minimum Spanning Tree
    • All Pair Shortest Path
  • Path Finding between two vertex

  • Determine Cycle in a Graph

  • To test if a graph is Bipartite

  • Topological Sort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment