Facebook
From Toxic Anoa, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 56
  1. #include<iostream>
  2. #include<vector>
  3. #define NODE 5
  4. using namespace std;
  5. int graph[NODE][NODE] = {{0, 0, 1, 1, 0},
  6.    {1, 0, 1, 0, 0},
  7.    {0, 0, 0, 1, 0},
  8.    {0, 1, 0, 0, 1},
  9.    {1, 0, 0, 0, 0}};
  10. void traverse(int u, bool visited[]) {
  11.    visited[u] = true; //mark v as visited
  12.    for(int v = 0; v<NODE; v++) {
  13.       if(graph[u][v]) {
  14.          if(!visited[v])
  15.             traverse(v, visited);
  16.       }
  17.    }
  18. }
  19. bool isConnected() {
  20.    bool *vis = new bool[NODE];
  21.    //for all vertex u as start point, check whether all nodes are visible or not
  22.    for(int u; u < NODE; u++) {
  23.       for(int i = 0; i<NODE; i++)
  24.          vis[i] = false; //initialize as no node is visited
  25.          traverse(u, vis);
  26.       for(int i = 0; i<NODE; i++) {
  27.          if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
  28.             return false;
  29.       }
  30.    }
  31.    return true;
  32. }
  33. bool hasEulerPath() {
  34.    int an = 0, bn = 0;
  35.    if(isConnected() == false){ //when graph is not connected
  36.       return false;
  37.    }
  38.    vector<int> inward(NODE, 0), outward(NODE, 0);
  39.    for(int i = 0; i<NODE; i++) {
  40.       int sum = 0;
  41.       for(int j = 0; j<NODE; j++) {
  42.          if(graph[i][j]) {
  43.             inward[j]++; //increase inward edge for destination vertex
  44.             sum++; //how many outward edge
  45.          }
  46.       }
  47.       outward[i] = sum;
  48.    }
  49.    //check the condition for Euler paths
  50.    if(inward == outward) //when number inward edges and outward edges for each node is same
  51.       return true; //Euler Circuit, it has Euler path
  52.    for(int i = 0; i<NODE; i++) {
  53.       if(inward[i] != outward[i]) {
  54.          if((inward[i] + 1 == outward[i])) {
  55.             an++;
  56.          } else if((inward[i] == outward[i] + 1)) {
  57.             bn++;
  58.          }
  59.       }
  60.    }
  61.    if(an == 1 && bn == 1) { //if there is only an, and bn, then this has euler path
  62.       return true;
  63.    }
  64.    return false;
  65. }
  66. int main() {
  67.    if(hasEulerPath())
  68.       cout << "Euler Path Found.";
  69.    else
  70.    cout << "There is no Euler Circuit.";
  71. }