Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

DFS (Depth First Traversal) in Data Structure: What is, Ordering & Applications

Updated on 29 September, 2022

11.09K+ views
7 min read

Meaning of DFS in Data Structure

DFS in Data Structure, also known as depth-first traversal, is a recursive algorithm primarily used to search all the vertices of a graph or tree data structure. Traversal is the visiting of every node of a graph. The algorithm begins from the root node (which may be an arbitrary node as the root node in a graph) and goes as far as it can along each branch before backtracking. 

The idea is to begin from the root or arbitrary node and keep the node marked. After this, you need to move to the adjacent node that is unmarked and continue this loop until there is no unmarked adjoining node. Then backtrack and examine the other nodes that are unmarked and traverse them. The final step is to print the nodes within the path.

Algorithm

Formulate a recursive function that will take the node’s index and a visited array.

  1.   Keep the current node marked as visited and then print it.
  2. Traverse all the adjoined notes and the unmarked ones and call the recursive function with the adjacent node’s index.

Properties

The analysis of time and space in the DFS in Data Structure varies according to its area of application. Theoretically, DFS is mainly used to cross a full graph and takes time O(|V|+|E|) where |V| depicts the number of vertexes and |E| depicts the number of edges. This graph is linear. 

In these applications, space O(|V|) is also used as a last resort to keep the stack of vertices stored on the search path and the set of vertices that are already visited. Therefore, the time and space bounds setting are similar to the breadth-first search. Here, the two algorithms used are less dependent on their complexity and more on the various characteristics of the vertex orders produced by the two algorithms. 

When it comes to applications of DFS in Data Structure related to specific domains, like finding solutions in web-crawling or AI, the graph that requires traversing might be too substantial to visit in totality. In such cases, the search is only executed to a restricted depth; due to finite resources, like disk space or memory. Data structures aren’t typically used to track the set of all the vertices visited previously. A search performed to a restricted depth still makes the time linear when it comes to the unit of expanded edges and vertexes. 

However, remember that this number does not have the same size as the entire graph since some of the vertexes may be searched multiple times and others not searched.

In such instances, DFS also turns to heuristic methods for selecting a more promising branch. Finally, when the appropriate depth limit cannot be determined, a priori, iterative deepening DFS is repeatedly applied via a sequence of growing limits. 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Depth First Search Algorithm

Each vertex of a graph in a standard DFS implementation is divided  into either of two categories:

  1.   Not Visited
  2.   Visited

The algorithm is used to pinpoint each vertex and mark them as visited and at the same time avoid cycles.

 This is how the DFS algorithm works:

  1.   Put any particular vertex of the graph on a stack.
  2.   The item on top of the stack should be added to the visited list.
  3.   Make a list of adjoining nodes of that vertex and add those not in the visited list on the top of the stack.
  4.   Keep repeating the previous steps till the stack empties.

DFS ordering

Vertex orderings: There are four ways of linearly ordering the vertexes of a graph or tree in DFS:

  1. The list of the vertexes arranged how they were visited first by the DFS algorithm is known as pre-ordering. It is a concise way to describe the search’s progress.
  2. The list of the vertexes in the order that they were visited last by the algorithm is known as post-ordering.
  3. The list of the vertexes in the order opposite to their first visit is a reverse pre-ordering. Therefore, it should not be mistaken for post ordering.
  4. The list of the vertexes in the order opposite to their last visit is a reverse post-ordering. It should not be mistaken for pre-ordering.

Additionally, there is in-ordering and reverse in-ordering for binary trees.

Depth First Search or DFS for a Graph 

The DFS for a graph is almost the same as the DFS for a tree. The only difference is that the graphs may have cycles, unlike trees. A node might be visited multiple times and to avoid processing the node, a Boolean visited array is used. 

Output Of A Depth First Search

The depth-first search is more easily depicted in terms of a spanning tree of the vertexes that are already reached in the search. Based on this spanning tree, the original graph edges are divided into three classes: the forward edges where the node of the tree is pointed towards one of its descendants, the back edges where the node is pointed towards one of its ancestors, and cross edges, which does neither of the previous functions.

Applications Of Depth First Traversal (DFS)

Depth-first search is used in the following algorithms as a building block:

  •         Searching for components that are connected.
  •         Finding 2-(vertex or edge)-connected components.
  •         Finding the graph’s bridges.
  •         Finding 3-(vertex or edge)-connected components.
  •         Topological sorting.
  •         Finding components that are strongly connected.
  •         Finding out if a species is similar to one or another species in a phylogenetic tree.
  •         Planarity testing.
  •         Producing words to determine the limit set of any group.
  •         Solving puzzles that have only one solution, like mazes.
  •         Maze generation.
  •         Searching for bi-connectivity in graphs.

DFS Pseudocode and Implementation in Python

The init() function is run on every node in the pseudocode below to ensure that all the vertexes are visited. This is especially important as graphs might have various disconnected areas.

Here is the pseudocode:

DFS(G, u)

    u.visited = true

    for each v ∈ G.Adj[u]

        if v.visited == false

            DFS(G,v)   

init() {

    For each u ∈ G

        u.visited = false

     For each u ∈ G

       DFS(G, u)

}

Here is the DFS implementation in Python:

graph = {

  ‘5’ : [‘3′,’7’],

  ‘2’ : [‘1’, ‘3’],

  ‘6’ : [‘7’],

  ‘3’ : [],

  ‘4’ : [‘6’],

  ‘7’ : []

}

visited = set()

def dfs(visited, graph, node): 

    if node not in visited:

        print (node)

        visited.add(node)

        for neighbour in graph[node]:

            dfs(visited, graph, neighbour)

print(“This is the DFS:”)

dfs(visited, graph, ‘5’)

Output: 

This is the DFS: 5

The complexity of Depth First Search

John Reif explored the computational complexity of Depth First Search. To be precise, in a graph, the given fact is G, let O be the standard order determined by the repetitive DFS algorithm. G represents the graph, and O represents the ordering output of the redundant DFS algorithm. This output is known as the lexicographic DFS ordering. 

Conclusion

The main goal of the DFS algorithm is visiting every single vertex that avoids cycles in target graphs. If you wish to get involved with advanced implementations of searching operations or ordering operations, you should definitely consider pursuing a premium and holistic course in Depth First Search and Data Structure.

upGrad has some top-tier DFS courses like Master of Science in Computer Science

 If you are struggling to take your next step and looking for some expert advice, upGrad Mentorship seeks to provide you with one-to-one sessions with the best career counsellors and experts in the industry.  

Frequently Asked Questions (FAQs)

1. What is the property or usage of a depth-first traversal?

The DFS or Depth First Search algorithm crosses a graph depthward and, to remember to obtain the next vertex for beginning a search, utilises a stack when it is met with a dead-end in an iteration.

2. Which data structure is used in depth-first traversal?

The data structure used for DFS is Stack. Stack is primarily used in any standard execution of DFS or Depth First Search.

3. What are the time and space requirements of the depth-first search algorithm?

O(|V|) is depicted as time complexity, where |V| is denoted as the number of nodes. All nodes must be traversed in this case. On the other hand, space complexity is also depicted as O(|V|) since in the ultimate scenario, all vertices need to be held in the queue.

RELATED PROGRAMS