In my previous post i wrote about implementation of Adjacency List in C++. So if you don't know how to implement Adjacency List in C++, you must read this post.
Depth First Search
DFS (in short) is a simple algorithm to traverse a graph.Lets understand the logic behind this algorithm with the help of following graph.
Blue > Green > Red |
Now i hope after reading this example you got the idea of graph traversal using DFS. So without wasting any time lets see the implementation part.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | int n = 100000; // Maximum number of nodes, change according to constraints. map<int, vector<int> > adjList; // Considering undirected graph bool visited[n]; void dfs(int u){ visited[u] = true; for(int i = 0 ; i < adjList[u].size() ; i ++){ int v = adjList[u][i]; // neighbour of u if(visited[v] != true){ // checking if neighbour is already visited or not dfs(v); } } } // inside int main memset(visited, 0, sizeof(visited)); /* * Take inputs and make Adjacency List */ dfs(1); // Let the starting vertex be 1 |
Adjacency List : O(V + E)
Adjacency Matrix : O(V*V)
where V = Number of vertices, E = Number of edges
Some of the applications of DFS :
- Topological sorting.
- Finding connected components.
- Finding the bridges of a graph.
- Finding the articulation points of a graph.
- Finding strongly connected components.
- Finding biconnectivity in graphs.
- Solving puzzles with only one solution, such as mazes.(You can use this in Robot maze solving competitions like in IIT Bombay's TechFest)
I will discuss each of them in detail in my next blog-posts.
This is my third blog-post and I hope you can now implement DFS very easily ! For any doubts you are most welcome and if you find any error in this post please help me correct it.THE END !
No comments:
Post a Comment