Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
C++ Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Weakly or Strongly Connected for a given a directed graph can be find out using DFS. This is a C++ program of this problem.
Functions used
Begin Function fillorder() = fill stack with all the vertices. a) Mark the current node as visited and print it b) Recur for all the vertices adjacent to this vertex c) All vertices reachable from v are processed by now, push v to Stack End Begin Function DFS() : a) Mark the current node as visited and print it b) Recur for all the vertices adjacent to this vertex End
Example
#include#include #include
using namespace std; class G { int m; list *adj; //declaration of functions void fillOrder(int n, bool visited[], stack &Stack); void DFS(int n, bool visited[]); public: G(int N); //constructor void addEd(int v, int w); int print(); G getTranspose(); }; G::G(int m) { this->m = m; adj = new list [m]; } void G::DFS(int n, bool visited[]) { visited[n] = true; // Mark the current node as visited and print it cout ::iterator i; //Recur for all the vertices adjacent to this vertex for (i = adj[n].begin(); i != adj[n].end(); ++i) if (!visited[*i]) DFS(*i, visited); } G G::getTranspose() { G g(m); for (int n = 0; n::iterator i; for (i = adj[n].begin(); i != adj[n].end(); ++i) { g.adj[*i].push_back(n); } } return g; } void G::addEd(int v, int w) { adj[v].push_back(w); //add w to v's list } void G::fillOrder(int v, bool visited[], stack &Stack) { visited[v] = true; //Mark the current node as visited and print it list ::iterator i; //Recur for all the vertices adjacent to this vertex for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); Stack.push(v); } int G::print() //print the solution { stack Stack; bool *visited = new bool[m]; for (int i = 0; i 1) { cout Output
Following are strongly connected components in given graph 4 0 1 2 3 Graph is weakly connected.
Advertisements
