Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS.
Pre-visit and Post-visit numbers are the extra information that can be stored while running a DFS on a graph and which turns out to be really useful. Pre-visit number tells the time at which the node gets into the recursion stack and Post-visit number tells the time at which the node comes out from recursion stack of DFS.
The numbers written in brackets denote [Pre-visit number, Post-visit number].
Pre and Post numbers are widely used in graph algorithms. For example, they can be used to find out whether a particular node lies in the sub-tree of another node.
To find whether u lies in the sub-tree of v or not we just compare the pre and post number of u and v. If pre[u] > pre[v] and post[u] < post[v] then u lies in the sub-tree of v otherwise not. You can see above example for more clarification.
Pre-visit and Post-visit numbers can be found out by simple DFS. We will take two arrays one for storing pre numbers and one for post numbers and by taking a variable which will keep track of the time. The implementation of the same is given below:
Node 1 Pre number 1 Post number 12 Node 2 Pre number 2 Post number 11 Node 3 Pre number 4 Post number 9 Node 4 Pre number 3 Post number 10 Node 5 Pre number 5 Post number 8 Node 6 Pre number 6 Post number 7
- Check if a cell can be visited more than once in a String
- Count the total number of squares that can be visited by Bishop in one move
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Detect cycle in the graph using degrees of nodes of graph
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Printing Triangle Pattern in Java
- Java Program for Dijkstra's Algorithm with Path Printing
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Fleury's Algorithm for printing Eulerian Path or Circuit
- Remove elements from the array which appear more than k times
- Find the value of XXXX.....(N times) % M where N is large
- String which when repeated exactly K times gives a permutation of S
- Count distinct substrings that contain some characters at most k times
- Round Robin Scheduling with different arrival times
- Largest element in the array that is repeated exactly k times
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.