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)