SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Graphs and Eulerian Path and Circuit
Graph:
A graph consists of a set of nodes represented by small circles, and a set of arcs
represented by lines. Graphs are mathematical concepts that have found many uses in computer
science. Graphs come in many different types, many of which have found uses in computer programs.
Some types are:
 Simple graph
 Undirected or directed graphs
 Cyclic or acyclic graphs
 labeled graphs
 Weighted graphs
 Infinite graphs
 ... and many more too numerous to mention.
Most graphs are defined as a slight alteration of the following rules.
 A graph is made up of two sets called Vertices and Edges.
 The Vertices are drawn from some underlying type, and the set may be finite or infinite.
 Each element of the Edge set is a pair consisting of two elements from the Vertices set.
 Graphs are often depicted visually, by drawing the elements of the Vertices set as boxes or
circles, and drawing the elements of the edge set as lines or arcs between the boxes or circles.
There is an arc between v1 and v2 if (v1,v2) is an element of the Edge set.
Adjacency:
If (u,v) is in the edge set we say u is adjacent to v (which we sometimes write as u ~ v). For example
the graph drawn below:
It has the following parts.
 The underlying set for the Vertices set is the integers.
 The Vertices set = {1,2,3,4,5,6}
 The Edge set = {(6,4),(4,5),(4,3),(3,2),(5,2),(2,1),(5,1)}
Different Kinds of Graphs
Various flavors of graphs have the following specializations and particulars about how they are usually
drawn.
 Undirected Graphs.
In an undirected graph, the order of the vertices in the pairs in the Edge set doesn't matter.
Thus, if we view the sample graph above we could have written the Edge set as
{(4,6),(4,5),(3,4),(3,2),(2,5)),(1,2)),(1,5)}. Undirected graphs usually are drawn with straight lines
between the vertices.
The adjacency relation is symmetric in an undirected graph, so if u ~ v then it is also the case
that v ~ u.
 Directed Graphs.
In a directed graph the order of the vertices in the pairs in the edge set matters. Thus u is
adjacent to v only if the pair (u,v) is in the Edge set. For directed graphs we usually use arrows
for the arcs between vertices. An arrow from u to v is drawn only if (u,v) is in the Edge set. The
directed graph below
It has the following parts:
o The underlying set for the Vertices set is capital letters.
o The Vertices set = {A,B,C,D,E}
o The Edge set = {(A,B),(B,C),(D,C),(B,D),(D,B),(E,D),(B,E)}
Note that both (B,D) and (D,B) are in the Edge set, so the arc between B and D is an arrow in
both directions.
 Vertex labeled Graphs.
In a labeled graph, each vertex is labeled with some data in addition to the data that identifies
the vertex. Only the indentifying data is present in the pair in the Edge set. This is silliar to the
(key,satellite) data distinction for sorting.
Here we have the following parts.
o The underlying set for the keys of the Vertices set is the integers.
o The underlying set for the satellite data is Color.
o The Vertices set = {(2,Blue),(4,Blue),(5,Red),(7,Green),(6,Red),(3,Yellow)}
o The Edge set = {(2,4),(4,5),(5,7),(7,6),(6,2),(4,3),(3,7)}
 Cyclic Graphs.
A cyclic graph is a directed graph with at least one cycle. A cycle is a path along the directed
edges from a vertex to itself. The vertex labeled graph above as several cycles. One of them is 2
» 4 » 5 » 7 » 6 » 2
 Edge labeled Graphs.
A Edge labeled graph is a graph where the edges are associated with labels. One can indicate this
be making the Edge set be a set of triples. Thus if (u,v,X) is in the edge set, then there is an edge
from u to v with label X.
Edge labeled graphs are usually drawn with the labels drawn adjacent to the arcs specifying the
edges.
Here we have the following parts.
o The underlying set for the the Vertices set is Color.
o The underlying set for the edge labels is sets of Color.
o The Vertices set = {Red,Green,Blue,White}
o The Edge set = {(red,white,{white,green}) ,(white,red,{blue}) ,(white,blue,{green,red})
,(red,blue,{blue}) ,(green,red,{red,blue,white}) ,(blue,green,{white,green,red})}
 Weighted Graphs.
A weighted graph is an edge labeled graph where the labels can be operated on by the usual
arithmetic operators, including comparisons like using less than and greater than. In Haskell
we'd say the edge labels are i the Num class. Usually they are integers or floats. The idea is that
some edges may be more (or less) expensive, and this cost is represented by the edge labels or
weight. In the graph below, which is an undirected graph, the weights are drawn adjacent to
the edges.
Here we have the following parts.
o The underlying set for the the Vertices set is Integer.
o The underlying set for the weights is Integer.
o The Vertices set = {1,2,3,4,5}
o The Edge set = {(1,4,5) ,(4,5,58) ,(3,5,34) ,(2,4,5) ,(2,5,4) ,(3,2,14) ,(1,2,2)}
 Directed Acyclic Graphs.
A Dag is a directed graph without cycles. They appear as special cases in CS applications all the
time.
Here we have the following parts.
o The underlying set for the the Vertices set is Integer.
o The Vertices set = {1,2,3,4,5,6,7,8}
o The Edge set = {(1,7) ,(2,6) ,(3,1),(3,5) ,(4,6) ,(5,4),(5,2) ,(6,8) ,(7,2),(7,8)}
 Disconnected Graphs
Vertices in a graph do not need to be connected to other vertices. It is legal for a graph to have
disconnected components, and even lone vertices without a single connection.
Vertices (like 5,7,and 8) with only in-arrows are called sinks. Vertices with only out-arrows (like
3 and 4) are called sources.
Here we have the following parts.
o The underlying set for the the Vertices set is Integer.
o The Vertices set = {1,2,3,4,5,6,7,8}
o The Edge set = {(1,7) ,(3,1),(3,8) ,(4,6) ,(6,5)}
Eulerian Path and Circuit
Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path
which starts and ends on the same vertex.
How to Find Whether a Given Graph is Eulerian or not?
The problem is same as following question. “Is it possible to draw a given graph without lifting pencil
from the paper and without tracing any of the edges more than once”.
A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path.
The problem seems similar to Hamiltonian Path which is NP complete problem for a general graph.
Fortunately, we can find whether a given graph has a Eulerian Path or not in polynomial time. In fact,
we can find it in O(V+E) time.
Following are some interesting properties of undirected graphs with an Eulerian path and cycle. We
can use these properties to find whether a graph is Eulerian or not.
 Eulerian Cycle
An undirected graph has Eulerian cycle if following two conditions are true.
a) All vertices with non-zero degree are connected. We don’t care about vertices with zero
degree because they don’t belong to Eulerian Cycle or Path (we only consider all edges).
b) All vertices have even degree.
 Eulerian Path
An undirected graph has Eulerian Path if following two conditions are true.
….a) Same as condition (a) for Eulerian Cycle
….b) If zero or two vertices have odd degree and all other vertices have even degree. Note that
only one vertex with odd degree is not possible in an undirected graph (sum of all degrees is
always even in an undirected graph)
Note that a graph with no edges is considered Eulerian because there are no edges to traverse.
How does this work?
In Eulerian path, each time we visit a vertex v, we walk through two unvisited edges with one end
point as v. Therefore, all middle vertices in Eulerian Path must have even degree. For Eulerian Cycle,
any vertex can be middle vertex, therefore all vertices must have even degree.
Another precedure used is Depth First Search (DFS)
 Depth First Search (DFS)
Basic Theory
Depth – first searches are performed by diving downward into a tree as quickly as possible. It
does this by always generating a child node from the most recently expanded node, then
generating that child’s children, and so on until a goal is found or some cutoff depth point d is
reached. If a goal is not found when a leaf node is reached or at the cutoff point, the program
backtracks to the most recently expanded node and generates another of its children. This
process continues until a goal is found or failure occurs.
Algorithm
An algorithm for the Depth First Search is the same as that for Breadth First Search except in
the ordering of the nodes.
1) Place the starting node s on the top of the stack.
2) If the stack is empty, return failure and stop.
3) If the element on the stack is goal node g, return success and stop. Otherwise,
4) Remove and expand the first element , and place the children at the top of the stack.
5) Return to step 2.
Example
Program of Eulerian Path and Circuit
Question: Given the ordered pairs of vertices associated to the
edgesof a directed multi graph, construct an Euler path or
Eulercircuit, if such a path or circuit exists.
Program is for Five Vertices Graph
Code:
// A C++ program to checkif a givengraphisEulerianornot
#include <iostream>
#include <list>
#include <conio.h>
usingnamespace std;
// A class that representsanundirectedgraph
classGraph
{
int V; // No.of vertices
list<int>*adj; // A dynamicarray of adjacencylists
public:
// Constructorand destructor
Graph(intV) {this->V =V; adj = newlist<int>[V];}
~Graph() { delete [] adj;} //To avoidmemoryleak
//functiontoadd an edge to graph
voidaddEdge(intv,intw);
// Methodto check if thisgraph isEulerianornot
int isEulerian();
// Methodto check if all non-zerodegree verticesare connected
bool isConnected();
// Functiontodo DFS startingfromv. Usedin isConnected();
voidDFSUtil(intv,bool visited[]);
};
voidGraph::addEdge(intv,intw)
{
adj[v].push_back(w);
adj[w].push_back(v); //Note:the graphisundirected
}
voidGraph::DFSUtil(intv,bool visited[])
{
// Mark the currentnode as visitedandprintit
visited[v] =true;
// Recur forall the verticesadjacenttothisvertex
list<int>::iteratori;
for (i = adj[v].begin();i !=adj[v].end();++i)
if (!visited[*i])
DFSUtil(*i,visited);
}
// Methodto checkif all non-zerodegreeverticesare connected.
// It mainlydoesDFStraversal startingfrom
bool Graph::isConnected()
{
// Mark all the verticesasnot visited
bool visited[V];
int i;
for (i = 0; i < V;i++)
visited[i] =false;
// Finda vertex withnon-zerodegree
for (i = 0; i < V;i++)
if (adj[i].size() !=0)
break;
// If there are no edgesinthe graph,returntrue
if (i == V)
returntrue;
// Start DFS traversal froma vertex withnon-zerodegree
DFSUtil(i,visited);
// Checkif all non-zerodegree verticesare visited
for (i = 0; i < V;i++)
if (visited[i] ==false &&adj[i].size() >0)
returnfalse;
returntrue;
}
/* The functionreturnsone of the followingvalues
0 -->If grpah isnot Eulerian
1 -->If graph hasan Eulerpath (Semi-Eulerian)
2 -->If graph hasan EulerCircuit(Eulerian) */
intGraph::isEulerian()
{
// Checkif all non-zerodegree verticesare connected
if (isConnected() ==false)
return0;
// Countverticeswithodddegree
int odd= 0;
for (inti = 0; i < V; i++)
if (adj[i].size() &1)
odd++;
// If count ismore than2, thengraphis not Eulerian
if (odd> 2)
return0;
// If odd countis 2, thensemi-eulerian.
// If odd countis 0, then eulerian
// Note that oddcount can neverbe 1 for undirectedgraph
return(odd)?1 : 2;
}
// Functiontorun testcases
voidtest(Graph&g)
{
int res= g.isEulerian();
if (res== 0)
cout<< "Graph is notEuleriann";
else if (res== 1)
cout<< "Graph has a Eulerpathn";
else
cout<< "Graph has a Eulercyclen";
}
// Driverprogramto testabove function
intmain()
{
// Letus create and testgraphs showninabove figures
intedge[10];
intedge1[12];
intedge2[12];
cout<<"tProgramto CheckEulerianCircuitor Pathof a Graph of Five Verticesn";
cout<<"t---------------------------------------------------------------------nn";
//EulerianPath
cout<<"Enter Edgesto CheckEulerianPath:n";
for (inti=0; i<10; i++)
{
cout<<"Vertex "<<i+1<<": ";
cin>>edge[i];
}
cout<<"Edge 1 is betweenVertices("<<edge[0]<<","<<edge[1]<<")n";
cout<<"Edge 2 is betweenVertices("<<edge[2]<<","<<edge[3]<<")n";
cout<<"Edge 3 is betweenVertices("<<edge[4]<<","<<edge[5]<<")n";
cout<<"Edge 4 is betweenVertices("<<edge[6]<<","<<edge[7]<<")n";
cout<<"Edge 5 is betweenVertices("<<edge[8]<<","<<edge[9]<<")n";
Graph g1(5);
g1.addEdge(edge[0],edge[1]);
g1.addEdge(edge[2],edge[3]);
g1.addEdge(edge[4],edge[5]);
g1.addEdge(edge[6],edge[7]);
g1.addEdge(edge[8],edge[9]);
cout<<"n";
test(g1);
cout<<"----------------------";
//EulerianCircuits
cout<<"nnEnterEdgestoCheckEulerianCircuit:n";
for (inti=0; i<12; i++)
{
cout<<"Vertex "<<i+1<<": ";
cin>>edge1[i];
}
cout<<"Edge 1 is betweenVertices("<<edge1[0]<<","<<edge1[1]<<")n";
cout<<"Edge 2 is betweenVertices("<<edge1[2]<<","<<edge1[3]<<")n";
cout<<"Edge 3 is betweenVertices("<<edge1[4]<<","<<edge1[5]<<")n";
cout<<"Edge 4 is betweenVertices("<<edge1[6]<<","<<edge1[7]<<")n";
cout<<"Edge 5 is betweenVertices("<<edge1[8]<<","<<edge1[9]<<")n";
cout<<"Edge 6 is betweenVertices("<<edge1[10]<<","<<edge1[11]<<")n";
Graph g2(5);
g2.addEdge(edge1[0],edge1[1]);
g2.addEdge(edge1[2],edge1[3]);
g2.addEdge(edge1[4],edge1[5]);
g2.addEdge(edge1[6],edge1[7]);
g2.addEdge(edge1[8],edge1[9]);
g2.addEdge(edge1[10],edge1[11]);
cout<<"n";
test(g2);
cout<<"-----------------------";
//NonEulerian
cout<<"nnEnterEdgesto CheckforNon EulerianCircuit:n";
for (inti=0; i<12; i++)
{
cout<<"Vertex "<<i+1<<": ";
cin>>edge2[i];
}
cout<<"Edge 1 is betweenVertices("<<edge2[0]<<","<<edge2[1]<<")n";
cout<<"Edge 2 is betweenVertices("<<edge2[2]<<","<<edge2[3]<<")n";
cout<<"Edge 3 is betweenVertices("<<edge2[4]<<","<<edge2[5]<<")n";
cout<<"Edge 4 is betweenVertices("<<edge2[6]<<","<<edge2[7]<<")n";
cout<<"Edge 5 is betweenVertices("<<edge2[8]<<","<<edge2[9]<<")n";
cout<<"Edge 6 is betweenVertices("<<edge2[10]<<","<<edge2[11]<<")n";
Graph g3(5);
g3.addEdge(edge2[0],edge2[1]);
g3.addEdge(edge2[2],edge2[3]);
g3.addEdge(edge2[4],edge2[5]);
g3.addEdge(edge2[6],edge2[7]);
g3.addEdge(edge2[8],edge2[9]);
g3.addEdge(edge2[10],edge2[11]);
cout<<"n";
test(g3);
cout<<"---------------------";
getche();
return0;
}
Output
Question: Given the ordered pairs of vertices associated to the edgesof a
directed multi graph, construct an Euler path or Eulercircuit, if such a path or
circuit exists.
Output for Path:
Path is (0,2,1,0,3,4)
Output for Circuit:
Circuit is (0,2,1,0,3,4,0)
Output For Non Eulerian:
NeitherCircuitNor Path
Graphs and eularian circuit & path with c++ program

Weitere ähnliche Inhalte

Was ist angesagt?

An overview of TCP (Transmission Control Protocol)
An overview of TCP (Transmission Control Protocol)An overview of TCP (Transmission Control Protocol)
An overview of TCP (Transmission Control Protocol)Ammad Marwat
 
Lab 4 Three-Bit Binary Adder
Lab 4 Three-Bit Binary AdderLab 4 Three-Bit Binary Adder
Lab 4 Three-Bit Binary AdderKatrina Little
 
Ethernet protocol
Ethernet protocolEthernet protocol
Ethernet protocolTom Chou
 
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networks
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networksBeginners: Bandwidth, Throughput, Latency & Jitter in mobile networks
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networks3G4G
 
Tipos de conexiones y meodelos del teclado y Mouse
Tipos de conexiones y meodelos del teclado y MouseTipos de conexiones y meodelos del teclado y Mouse
Tipos de conexiones y meodelos del teclado y MouseRonaldSteven17
 
Wishbone classic bus cycle
Wishbone classic bus cycleWishbone classic bus cycle
Wishbone classic bus cycledennis gookyi
 

Was ist angesagt? (11)

An overview of TCP (Transmission Control Protocol)
An overview of TCP (Transmission Control Protocol)An overview of TCP (Transmission Control Protocol)
An overview of TCP (Transmission Control Protocol)
 
Arduino & NodeMcu
Arduino & NodeMcuArduino & NodeMcu
Arduino & NodeMcu
 
Wired LANs
Wired LANsWired LANs
Wired LANs
 
Lab 4 Three-Bit Binary Adder
Lab 4 Three-Bit Binary AdderLab 4 Three-Bit Binary Adder
Lab 4 Three-Bit Binary Adder
 
Ethernet protocol
Ethernet protocolEthernet protocol
Ethernet protocol
 
Blackfin core architecture
Blackfin core architectureBlackfin core architecture
Blackfin core architecture
 
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networks
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networksBeginners: Bandwidth, Throughput, Latency & Jitter in mobile networks
Beginners: Bandwidth, Throughput, Latency & Jitter in mobile networks
 
Tipos de conexiones y meodelos del teclado y Mouse
Tipos de conexiones y meodelos del teclado y MouseTipos de conexiones y meodelos del teclado y Mouse
Tipos de conexiones y meodelos del teclado y Mouse
 
Wishbone classic bus cycle
Wishbone classic bus cycleWishbone classic bus cycle
Wishbone classic bus cycle
 
Vhdl programming
Vhdl programmingVhdl programming
Vhdl programming
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 

Ähnlich wie Graphs and eularian circuit & path with c++ program

Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptxARVIND SARDAR
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx pptDhruvilSTATUS
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxbashirabdullah789
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________ssuser1989da
 
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringSaurabh Kaushik
 
Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabatinabati
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaPyData
 

Ähnlich wie Graphs and eularian circuit & path with c++ program (20)

Graphs
GraphsGraphs
Graphs
 
Graph
GraphGraph
Graph
 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 
ppt 1.pptx
ppt 1.pptxppt 1.pptx
ppt 1.pptx
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx ppt
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________
 
Graphs
GraphsGraphs
Graphs
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Graphs.pptx
Graphs.pptxGraphs.pptx
Graphs.pptx
 
18 Basic Graph Algorithms
18 Basic Graph Algorithms18 Basic Graph Algorithms
18 Basic Graph Algorithms
 
Graph 1
Graph 1Graph 1
Graph 1
 
Introduction to Graph Theory
Introduction to Graph TheoryIntroduction to Graph Theory
Introduction to Graph Theory
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
 
UNIT III.pptx
UNIT III.pptxUNIT III.pptx
UNIT III.pptx
 
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
 
Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabati
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
 

Mehr von Muhammad Danish Badar

Mehr von Muhammad Danish Badar (8)

Water and marketing needs, wants & demands
Water and marketing needs, wants & demandsWater and marketing needs, wants & demands
Water and marketing needs, wants & demands
 
Vocabulary builiding strategy
Vocabulary builiding strategyVocabulary builiding strategy
Vocabulary builiding strategy
 
Napoleon Bonaparte
Napoleon BonaparteNapoleon Bonaparte
Napoleon Bonaparte
 
Differences Between British English and American English
Differences Between British English and American EnglishDifferences Between British English and American English
Differences Between British English and American English
 
Library Managment System - C++ Program
Library Managment System - C++ ProgramLibrary Managment System - C++ Program
Library Managment System - C++ Program
 
Alexander the great
Alexander the greatAlexander the great
Alexander the great
 
Adolf hitler
Adolf hitlerAdolf hitler
Adolf hitler
 
Comparison between computers of past and present
Comparison between computers of past and presentComparison between computers of past and present
Comparison between computers of past and present
 

Kürzlich hochgeladen

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Kürzlich hochgeladen (20)

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 

Graphs and eularian circuit & path with c++ program

  • 1. Graphs and Eulerian Path and Circuit Graph: A graph consists of a set of nodes represented by small circles, and a set of arcs represented by lines. Graphs are mathematical concepts that have found many uses in computer science. Graphs come in many different types, many of which have found uses in computer programs. Some types are:  Simple graph  Undirected or directed graphs  Cyclic or acyclic graphs  labeled graphs  Weighted graphs  Infinite graphs  ... and many more too numerous to mention. Most graphs are defined as a slight alteration of the following rules.  A graph is made up of two sets called Vertices and Edges.  The Vertices are drawn from some underlying type, and the set may be finite or infinite.  Each element of the Edge set is a pair consisting of two elements from the Vertices set.  Graphs are often depicted visually, by drawing the elements of the Vertices set as boxes or circles, and drawing the elements of the edge set as lines or arcs between the boxes or circles. There is an arc between v1 and v2 if (v1,v2) is an element of the Edge set. Adjacency: If (u,v) is in the edge set we say u is adjacent to v (which we sometimes write as u ~ v). For example the graph drawn below: It has the following parts.  The underlying set for the Vertices set is the integers.  The Vertices set = {1,2,3,4,5,6}  The Edge set = {(6,4),(4,5),(4,3),(3,2),(5,2),(2,1),(5,1)}
  • 2. Different Kinds of Graphs Various flavors of graphs have the following specializations and particulars about how they are usually drawn.  Undirected Graphs. In an undirected graph, the order of the vertices in the pairs in the Edge set doesn't matter. Thus, if we view the sample graph above we could have written the Edge set as {(4,6),(4,5),(3,4),(3,2),(2,5)),(1,2)),(1,5)}. Undirected graphs usually are drawn with straight lines between the vertices. The adjacency relation is symmetric in an undirected graph, so if u ~ v then it is also the case that v ~ u.  Directed Graphs. In a directed graph the order of the vertices in the pairs in the edge set matters. Thus u is adjacent to v only if the pair (u,v) is in the Edge set. For directed graphs we usually use arrows for the arcs between vertices. An arrow from u to v is drawn only if (u,v) is in the Edge set. The directed graph below It has the following parts: o The underlying set for the Vertices set is capital letters. o The Vertices set = {A,B,C,D,E} o The Edge set = {(A,B),(B,C),(D,C),(B,D),(D,B),(E,D),(B,E)} Note that both (B,D) and (D,B) are in the Edge set, so the arc between B and D is an arrow in both directions.
  • 3.  Vertex labeled Graphs. In a labeled graph, each vertex is labeled with some data in addition to the data that identifies the vertex. Only the indentifying data is present in the pair in the Edge set. This is silliar to the (key,satellite) data distinction for sorting. Here we have the following parts. o The underlying set for the keys of the Vertices set is the integers. o The underlying set for the satellite data is Color. o The Vertices set = {(2,Blue),(4,Blue),(5,Red),(7,Green),(6,Red),(3,Yellow)} o The Edge set = {(2,4),(4,5),(5,7),(7,6),(6,2),(4,3),(3,7)}  Cyclic Graphs. A cyclic graph is a directed graph with at least one cycle. A cycle is a path along the directed edges from a vertex to itself. The vertex labeled graph above as several cycles. One of them is 2 » 4 » 5 » 7 » 6 » 2  Edge labeled Graphs. A Edge labeled graph is a graph where the edges are associated with labels. One can indicate this be making the Edge set be a set of triples. Thus if (u,v,X) is in the edge set, then there is an edge from u to v with label X. Edge labeled graphs are usually drawn with the labels drawn adjacent to the arcs specifying the edges.
  • 4. Here we have the following parts. o The underlying set for the the Vertices set is Color. o The underlying set for the edge labels is sets of Color. o The Vertices set = {Red,Green,Blue,White} o The Edge set = {(red,white,{white,green}) ,(white,red,{blue}) ,(white,blue,{green,red}) ,(red,blue,{blue}) ,(green,red,{red,blue,white}) ,(blue,green,{white,green,red})}  Weighted Graphs. A weighted graph is an edge labeled graph where the labels can be operated on by the usual arithmetic operators, including comparisons like using less than and greater than. In Haskell we'd say the edge labels are i the Num class. Usually they are integers or floats. The idea is that some edges may be more (or less) expensive, and this cost is represented by the edge labels or weight. In the graph below, which is an undirected graph, the weights are drawn adjacent to the edges. Here we have the following parts. o The underlying set for the the Vertices set is Integer. o The underlying set for the weights is Integer. o The Vertices set = {1,2,3,4,5}
  • 5. o The Edge set = {(1,4,5) ,(4,5,58) ,(3,5,34) ,(2,4,5) ,(2,5,4) ,(3,2,14) ,(1,2,2)}  Directed Acyclic Graphs. A Dag is a directed graph without cycles. They appear as special cases in CS applications all the time. Here we have the following parts. o The underlying set for the the Vertices set is Integer. o The Vertices set = {1,2,3,4,5,6,7,8} o The Edge set = {(1,7) ,(2,6) ,(3,1),(3,5) ,(4,6) ,(5,4),(5,2) ,(6,8) ,(7,2),(7,8)}  Disconnected Graphs Vertices in a graph do not need to be connected to other vertices. It is legal for a graph to have disconnected components, and even lone vertices without a single connection. Vertices (like 5,7,and 8) with only in-arrows are called sinks. Vertices with only out-arrows (like 3 and 4) are called sources. Here we have the following parts. o The underlying set for the the Vertices set is Integer. o The Vertices set = {1,2,3,4,5,6,7,8} o The Edge set = {(1,7) ,(3,1),(3,8) ,(4,6) ,(6,5)}
  • 6. Eulerian Path and Circuit Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. How to Find Whether a Given Graph is Eulerian or not? The problem is same as following question. “Is it possible to draw a given graph without lifting pencil from the paper and without tracing any of the edges more than once”. A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path. The problem seems similar to Hamiltonian Path which is NP complete problem for a general graph. Fortunately, we can find whether a given graph has a Eulerian Path or not in polynomial time. In fact, we can find it in O(V+E) time.
  • 7. Following are some interesting properties of undirected graphs with an Eulerian path and cycle. We can use these properties to find whether a graph is Eulerian or not.  Eulerian Cycle An undirected graph has Eulerian cycle if following two conditions are true. a) All vertices with non-zero degree are connected. We don’t care about vertices with zero degree because they don’t belong to Eulerian Cycle or Path (we only consider all edges). b) All vertices have even degree.  Eulerian Path An undirected graph has Eulerian Path if following two conditions are true. ….a) Same as condition (a) for Eulerian Cycle ….b) If zero or two vertices have odd degree and all other vertices have even degree. Note that only one vertex with odd degree is not possible in an undirected graph (sum of all degrees is always even in an undirected graph) Note that a graph with no edges is considered Eulerian because there are no edges to traverse. How does this work? In Eulerian path, each time we visit a vertex v, we walk through two unvisited edges with one end point as v. Therefore, all middle vertices in Eulerian Path must have even degree. For Eulerian Cycle, any vertex can be middle vertex, therefore all vertices must have even degree. Another precedure used is Depth First Search (DFS)  Depth First Search (DFS) Basic Theory Depth – first searches are performed by diving downward into a tree as quickly as possible. It does this by always generating a child node from the most recently expanded node, then generating that child’s children, and so on until a goal is found or some cutoff depth point d is reached. If a goal is not found when a leaf node is reached or at the cutoff point, the program backtracks to the most recently expanded node and generates another of its children. This process continues until a goal is found or failure occurs. Algorithm An algorithm for the Depth First Search is the same as that for Breadth First Search except in the ordering of the nodes. 1) Place the starting node s on the top of the stack. 2) If the stack is empty, return failure and stop. 3) If the element on the stack is goal node g, return success and stop. Otherwise, 4) Remove and expand the first element , and place the children at the top of the stack. 5) Return to step 2.
  • 8. Example Program of Eulerian Path and Circuit Question: Given the ordered pairs of vertices associated to the edgesof a directed multi graph, construct an Euler path or Eulercircuit, if such a path or circuit exists. Program is for Five Vertices Graph Code: // A C++ program to checkif a givengraphisEulerianornot #include <iostream> #include <list> #include <conio.h> usingnamespace std; // A class that representsanundirectedgraph classGraph { int V; // No.of vertices list<int>*adj; // A dynamicarray of adjacencylists public: // Constructorand destructor Graph(intV) {this->V =V; adj = newlist<int>[V];} ~Graph() { delete [] adj;} //To avoidmemoryleak //functiontoadd an edge to graph voidaddEdge(intv,intw); // Methodto check if thisgraph isEulerianornot int isEulerian(); // Methodto check if all non-zerodegree verticesare connected
  • 9. bool isConnected(); // Functiontodo DFS startingfromv. Usedin isConnected(); voidDFSUtil(intv,bool visited[]); }; voidGraph::addEdge(intv,intw) { adj[v].push_back(w); adj[w].push_back(v); //Note:the graphisundirected } voidGraph::DFSUtil(intv,bool visited[]) { // Mark the currentnode as visitedandprintit visited[v] =true; // Recur forall the verticesadjacenttothisvertex list<int>::iteratori; for (i = adj[v].begin();i !=adj[v].end();++i) if (!visited[*i]) DFSUtil(*i,visited); } // Methodto checkif all non-zerodegreeverticesare connected. // It mainlydoesDFStraversal startingfrom bool Graph::isConnected() { // Mark all the verticesasnot visited bool visited[V]; int i; for (i = 0; i < V;i++) visited[i] =false; // Finda vertex withnon-zerodegree for (i = 0; i < V;i++) if (adj[i].size() !=0) break; // If there are no edgesinthe graph,returntrue if (i == V) returntrue; // Start DFS traversal froma vertex withnon-zerodegree DFSUtil(i,visited); // Checkif all non-zerodegree verticesare visited for (i = 0; i < V;i++) if (visited[i] ==false &&adj[i].size() >0) returnfalse; returntrue; }
  • 10. /* The functionreturnsone of the followingvalues 0 -->If grpah isnot Eulerian 1 -->If graph hasan Eulerpath (Semi-Eulerian) 2 -->If graph hasan EulerCircuit(Eulerian) */ intGraph::isEulerian() { // Checkif all non-zerodegree verticesare connected if (isConnected() ==false) return0; // Countverticeswithodddegree int odd= 0; for (inti = 0; i < V; i++) if (adj[i].size() &1) odd++; // If count ismore than2, thengraphis not Eulerian if (odd> 2) return0; // If odd countis 2, thensemi-eulerian. // If odd countis 0, then eulerian // Note that oddcount can neverbe 1 for undirectedgraph return(odd)?1 : 2; } // Functiontorun testcases voidtest(Graph&g) { int res= g.isEulerian(); if (res== 0) cout<< "Graph is notEuleriann"; else if (res== 1) cout<< "Graph has a Eulerpathn"; else cout<< "Graph has a Eulercyclen"; } // Driverprogramto testabove function intmain() { // Letus create and testgraphs showninabove figures intedge[10]; intedge1[12]; intedge2[12]; cout<<"tProgramto CheckEulerianCircuitor Pathof a Graph of Five Verticesn"; cout<<"t---------------------------------------------------------------------nn"; //EulerianPath cout<<"Enter Edgesto CheckEulerianPath:n"; for (inti=0; i<10; i++) {
  • 11. cout<<"Vertex "<<i+1<<": "; cin>>edge[i]; } cout<<"Edge 1 is betweenVertices("<<edge[0]<<","<<edge[1]<<")n"; cout<<"Edge 2 is betweenVertices("<<edge[2]<<","<<edge[3]<<")n"; cout<<"Edge 3 is betweenVertices("<<edge[4]<<","<<edge[5]<<")n"; cout<<"Edge 4 is betweenVertices("<<edge[6]<<","<<edge[7]<<")n"; cout<<"Edge 5 is betweenVertices("<<edge[8]<<","<<edge[9]<<")n"; Graph g1(5); g1.addEdge(edge[0],edge[1]); g1.addEdge(edge[2],edge[3]); g1.addEdge(edge[4],edge[5]); g1.addEdge(edge[6],edge[7]); g1.addEdge(edge[8],edge[9]); cout<<"n"; test(g1); cout<<"----------------------"; //EulerianCircuits cout<<"nnEnterEdgestoCheckEulerianCircuit:n"; for (inti=0; i<12; i++) { cout<<"Vertex "<<i+1<<": "; cin>>edge1[i]; } cout<<"Edge 1 is betweenVertices("<<edge1[0]<<","<<edge1[1]<<")n"; cout<<"Edge 2 is betweenVertices("<<edge1[2]<<","<<edge1[3]<<")n"; cout<<"Edge 3 is betweenVertices("<<edge1[4]<<","<<edge1[5]<<")n"; cout<<"Edge 4 is betweenVertices("<<edge1[6]<<","<<edge1[7]<<")n"; cout<<"Edge 5 is betweenVertices("<<edge1[8]<<","<<edge1[9]<<")n"; cout<<"Edge 6 is betweenVertices("<<edge1[10]<<","<<edge1[11]<<")n"; Graph g2(5); g2.addEdge(edge1[0],edge1[1]); g2.addEdge(edge1[2],edge1[3]); g2.addEdge(edge1[4],edge1[5]); g2.addEdge(edge1[6],edge1[7]); g2.addEdge(edge1[8],edge1[9]); g2.addEdge(edge1[10],edge1[11]); cout<<"n"; test(g2); cout<<"-----------------------"; //NonEulerian cout<<"nnEnterEdgesto CheckforNon EulerianCircuit:n"; for (inti=0; i<12; i++) { cout<<"Vertex "<<i+1<<": "; cin>>edge2[i]; } cout<<"Edge 1 is betweenVertices("<<edge2[0]<<","<<edge2[1]<<")n"; cout<<"Edge 2 is betweenVertices("<<edge2[2]<<","<<edge2[3]<<")n"; cout<<"Edge 3 is betweenVertices("<<edge2[4]<<","<<edge2[5]<<")n"; cout<<"Edge 4 is betweenVertices("<<edge2[6]<<","<<edge2[7]<<")n";
  • 12. cout<<"Edge 5 is betweenVertices("<<edge2[8]<<","<<edge2[9]<<")n"; cout<<"Edge 6 is betweenVertices("<<edge2[10]<<","<<edge2[11]<<")n"; Graph g3(5); g3.addEdge(edge2[0],edge2[1]); g3.addEdge(edge2[2],edge2[3]); g3.addEdge(edge2[4],edge2[5]); g3.addEdge(edge2[6],edge2[7]); g3.addEdge(edge2[8],edge2[9]); g3.addEdge(edge2[10],edge2[11]); cout<<"n"; test(g3); cout<<"---------------------"; getche(); return0; } Output Question: Given the ordered pairs of vertices associated to the edgesof a directed multi graph, construct an Euler path or Eulercircuit, if such a path or circuit exists. Output for Path: Path is (0,2,1,0,3,4)
  • 13. Output for Circuit: Circuit is (0,2,1,0,3,4,0) Output For Non Eulerian: NeitherCircuitNor Path