Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Kosaraju’s Algorithm in C++
Next article icon

Tarjan’s Algorithm in C++

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this post, we will see the implementation of Tarjan’s Algorithm in C++ language.

What is Tarjan’s Algorithm?

Tarjan’s Algorithm is a well-known algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every other vertex in the subgraph. This algorithm has various applications such as detecting cycles in graphs, designing circuits, and analyzing networks.

stronglyCOnnectedComponent
Strongly Connected Component

How does Tarjan’s Algorithm work in C++?

The algorithm uses a depth-first search (DFS) to traverse the graph. It keeps track of the discovery times and the lowest discovery times of the vertices. Using a stack, it identifies SCCs when the current vertex’s discovery time matches the lowest discovery time of any vertex reachable from it.

Steps to Implement Tarjan’s Algorithm in C++

  1. Initialize arrays to store the discovery time and the lowest discovery time of vertices.
  2. Use a stack to keep track of the vertices in the current path.
  3. Perform DFS on each vertex:
    • Set the discovery time and the lowest discovery time.
    • Push the vertex onto the stack.
    • For each adjacent vertex, if it is not visited, recursively perform DFS on it and update the lowest discovery time. If it is already on the stack, update the lowest discovery time.
  4. If the vertex’s discovery time matches the lowest discovery time, pop vertices from the stack until the current vertex is reached to form an SCC.
  5. Repeat for all vertices.

Working of Tarjan’s Algorithm in C++

The below example illustrates a step-by-step implementation of Tarjan’s Algorithm.

Tarjansresize
Tarjan's Algorithm

C++ Program to Implement Tarjan’s Algorithm

Below is a C++ program that implements Tarjan’s Algorithm for finding strongly connected components:

C++
// A C++ program to find strongly connected components in a // given directed graph using Tarjan's algorithm (single // DFS) #include <algorithm> #include <iostream> #include <list> #include <stack> #include <vector>  #define NIL -1 using namespace std;  // A class that represents a directed graph class Graph {     int V; // No. of vertices     list<int>* adj; // A dynamic array of adjacency lists      // A Recursive DFS based function used by SCC()     void SCCUtil(int u, int disc[], int low[],                  stack<int>* st, bool stackMember[]);  public:     Graph(int V); // Constructor     void     addEdge(int v,             int w); // function to add an edge to the graph     void SCC(); // prints strongly connected components };  Graph::Graph(int V) {     this->V = V;     adj = new list<int>[V]; }  void Graph::addEdge(int v, int w) { adj[v].push_back(w); }  // A recursive function that finds and prints strongly // connected components using DFS traversal void Graph::SCCUtil(int u, int disc[], int low[],                     stack<int>* st, bool stackMember[]) {     // A static variable is used for simplicity, we can     // avoid use of static variable by passing a pointer.     static int time = 0;      // Initialize discovery time and low value     disc[u] = low[u] = ++time;     st->push(u);     stackMember[u] = true;      // Go through all vertices adjacent to this     list<int>::iterator i;     for (i = adj[u].begin(); i != adj[u].end(); ++i) {         int v = *i; // v is current adjacent of 'u'          // If v is not visited yet, then recur for it         if (disc[v] == -1) {             SCCUtil(v, disc, low, st, stackMember);              // Check if the subtree rooted with 'v' has a             // connection to one of the ancestors of 'u'             low[u] = min(low[u], low[v]);         }         // Update low value of 'u' only if 'v' is still in         // stack (i.e., it's a back edge, not a cross edge)         else if (stackMember[v] == true)             low[u] = min(low[u], disc[v]);     }      // Head node found, pop the stack and print an SCC     int w = 0; // To store stack extracted vertices     if (low[u] == disc[u]) {         while (st->top() != u) {             w = (int)st->top();             cout << w << " ";             stackMember[w] = false;             st->pop();         }         w = (int)st->top();         cout << w << "\n";         stackMember[w] = false;         st->pop();     } }  // The function to do DFS traversal. It uses SCCUtil() void Graph::SCC() {     int* disc = new int[V];     int* low = new int[V];     bool* stackMember = new bool[V];     stack<int>* st = new stack<int>();      // Initialize disc and low, and stackMember arrays     for (int i = 0; i < V; i++) {         disc[i] = NIL;         low[i] = NIL;         stackMember[i] = false;     }      // Call the recursive helper function to find strongly     // connected components in DFS tree with vertex 'i'     for (int i = 0; i < V; i++)         if (disc[i] == NIL)             SCCUtil(i, disc, low, st, stackMember);      // Free allocated memory     delete[] disc;     delete[] low;     delete[] stackMember;     delete st; }  // Driver program to test above function int main() {     cout << "\nSCCs in first graph \n";     Graph g1(5);     g1.addEdge(1, 0);     g1.addEdge(0, 2);     g1.addEdge(2, 1);     g1.addEdge(0, 3);     g1.addEdge(3, 4);     g1.SCC();      cout << "\nSCCs in second graph \n";     Graph g2(4);     g2.addEdge(0, 1);     g2.addEdge(1, 2);     g2.addEdge(2, 3);     g2.SCC();      cout << "\nSCCs in third graph \n";     Graph g3(7);     g3.addEdge(0, 1);     g3.addEdge(1, 2);     g3.addEdge(2, 0);     g3.addEdge(1, 3);     g3.addEdge(1, 4);     g3.addEdge(1, 6);     g3.addEdge(3, 5);     g3.addEdge(4, 5);     g3.SCC();      cout << "\nSCCs in fourth graph \n";     Graph g4(11);     g4.addEdge(0, 1);     g4.addEdge(0, 3);     g4.addEdge(1, 2);     g4.addEdge(1, 4);     g4.addEdge(2, 0);     g4.addEdge(2, 6);     g4.addEdge(3, 2);     g4.addEdge(4, 5);     g4.addEdge(4, 6);     g4.addEdge(5, 6);     g4.addEdge(5, 7);     g4.addEdge(5, 8);     g4.addEdge(5, 9);     g4.addEdge(6, 4);     g4.addEdge(7, 9);     g4.addEdge(8, 9);     g4.addEdge(9, 8);     g4.SCC();      cout << "\nSCCs in fifth graph \n";     Graph g5(5);     g5.addEdge(0, 1);     g5.addEdge(1, 2);     g5.addEdge(2, 3);     g5.addEdge(2, 4);     g5.addEdge(3, 0);     g5.addEdge(4, 2);     g5.SCC();      return 0; } 

Output
SCCs in first graph  4 3 1 2 0  SCCs in second graph  3 2 1 0  SCCs in third graph  5 3 4 6 2 1 0  SCCs in fourth graph  8 9 7 5 4 6 3 2 1 0 10  SCCs in fifth graph  4 3 2 1 0 

Time Complexity: The above algorithm mainly calls DFS, DFS takes O(V+E) for a graph represented using an adjacency list. 
Auxiliary Space: O(V)

Applications of Tarjan’s Algorithm

  • Courses at universities often have prerequisites. Tarjan’s algorithm can help schedule courses so that prerequisites are taken before the courses that require them.
  • In software development, libraries and modules often depend on others. Tarjan’s algorithm helps resolve dependencies in the correct order.
  • Tasks in project management often depend on one another. Tarjan’s method can schedule tasks so that dependent tasks are completed before those that rely on them.
  • Some processes in data processing pipelines depend on the results of others. Tarjan’s algorithm ensures stages are executed in the correct order.
  • In designing electronic circuits, some components depend on the output of others. Tarjan’s algorithm helps connect components in the proper sequence.

Next Article
Kosaraju’s Algorithm in C++
author
bug8wdqo
Improve
Article Tags :
  • C++
  • CPP-DSA
Practice Tags :
  • CPP

Similar Reads

  • Tarjan’s Algorithm in C Language
    In this post, we will see the implementation of Tarjan's Algorithm in C language. What is Tarjan's Algorithm?Tarjan's Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every ot
    5 min read
  • Kosaraju’s Algorithm in C++
    In this post, we will see the implementation of Kosaraju’s Algorithm in C++. What is Kosaraju’s Algorithm?Kosaraju’s Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every oth
    4 min read
  • Kahn’s Algorithm in C++
    In this post, we will see the implementation of Kahn’s Algorithm in C++. What is Kahn’s Algorithm?Kahn’s Algorithm is a classic algorithm used for topological sorting of a directed acyclic graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge u -> v,
    4 min read
  • Prim's Algorithm in C++
    Prim's Algorithm is a greedy algorithm that is used to find the Minimum Spanning Tree (MST) for a weighted, undirected graph. MST is a subset of the graph's edges that connects all vertices together without any cycles and with the minimum possible total edge weight In this article, we will learn the
    6 min read
  • Prim's Algorithm in C
    Prim’s algorithm is a greedy algorithm that finds the minimum spanning tree (MST) for a weighted undirected graph. It starts with a single vertex and grows the MST one edge at a time by adding the smallest edge that connects a vertex in the MST to a vertex outside the MST. In this article, we will l
    6 min read
  • Kahn’s Algorithm in C Language
    In this post, we will see the implementation of Kahn's Algorithm in C language. What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every dire
    5 min read
  • Convex Hull Algorithm in C++
    The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geogr
    15+ min read
  • Algorithm Library Functions in C++ STL
    Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Fin
    4 min read
  • Implementation of Rabin Karp Algorithm in C++
    The Rabin-Karp Algorithm is a string-searching algorithm that efficiently finds a pattern within a text using hashing. It is particularly useful for finding multiple patterns in the same text or for searching in streams of data. In this article, we will learn how to implement the Rabin-Karp Algorith
    5 min read
  • boost::algorithm::clamp() in C++ library
    The clamp() function in C++ boost library is found under the header 'boost/algorithm/clamp.hpp' contains two functions for "clamping" a value between a pair of boundary values. Syntax: const T& clamp ( const T& val, const T& lo, const T& hi ) or const T& clamp ( const T& valu
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences