
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Convert the undirected graph into directed graph such that there is no path of length greater than 1 in C++
In this tutorial, we will be discussing a program to convert the undirected graph into a directed graph such that there is no path of length greater than 1.
For this we will be provided with an undirected graph. Our task is to convert that graph into a direct one given no path has a length greater than 1.
Example
#include <bits/stdc++.h> using namespace std; #define N 100005 //storing the graph vector<int> gr[N]; //storing colour of each vertex int colour[N]; vector<pair<int, int> > edges; bool bip; //adding edges to the graph void add_edge(int x, int y){ gr[x].push_back(y); gr[y].push_back(x); edges.push_back(make_pair(x, y)); } //checking if the given graph //is bipartite void dfs(int x, int col){ colour[x] = col; //moving to the child vertices for (auto i : gr[x]) { if (colour[i] == -1) dfs(i, col ^ 1); //if child and parent having //same branch else if (colour[i] == col) bip = false; } } //converting into direct graph void convert_directed(int n, int m){ memset(colour, -1, sizeof colour); bip = true; //calling bipartite function dfs(1, 1); if (!bip) { cout << -1; return; } //if bipartite is possible for (int i = 0; i < m; i++) { if (colour[edges[i].first] == 0) swap(edges[i].first, edges[i].second); cout << edges[i].first << " " << edges[i].second << endl; } } int main(){ int n = 4, m = 3; add_edge(1, 2); add_edge(1, 3); add_edge(1, 4); convert_directed(n, m); return 0; }
Output
1 2 1 3 1 4
- Related Articles
- Longest Path in a Directed Acyclic Graph
- Shortest Path in a Directed Acyclic Graph
- C++ Program to Check Whether an Undirected Graph Contains a Eulerian Path
- C++ Program to Check Whether a Directed Graph Contains a Eulerian Path
- Connectivity in a directed graph
- Directed Acyclic Graph (DAG)
- Number of Connected Components in an Undirected Graph in C++
- Count number of edges in an undirected graph in C++
- Print all the cycles in an undirected graph in C++
- Detect Cycle in a Directed Graph
- Euler Circuit in a Directed Graph
- How to convert ggplot2 graph into a plotly graph in R?
- Check if a given directed graph is strongly connected in C++
- Check if a directed graph is connected or not in C++
- C++ Program to Check the Connectivity of Undirected Graph Using BFS

Advertisements