Monday, July 21, 2014

Judge whether a undirected graph is a Tree

Question:
To judge whether a undirected graph is a Tree (don't have specify the d-ary value of tree...)
(== judge whether a undirected graph is acyclic) For a undirected graph, acyclic graph is just a tree.

Answer:
Key point:
1. Exclude the "root" node, every node can only has '1' parent;
2. Every node can have many children nodes.
3. Should notice about how many connectd components there are. (including isolated node)

#include <stdio.h>
#include <unordered_set>
#include <vector>
#include <iostream>

using namespace std;

struct GNode{
int val;
vector<GNode*> connection;
};

bool JudgeGTHelp(GNode *cur,GNode *par, unordered_set<GNode*> &sset){
if(!cur) return false;
    if(cur->connection.size()==1 && cur->connection[0] == par) return true;     //leaf node, only has '1' parent, base case.

for(int i=0; i<cur->connection.size();++i){
GNode *p = cur->connection[i];
if(p == par) continue;

if(sset.find(p)!= sset.end()) return false;    //To ensure the child node only has '1' parent,i.e.==cur, not traversed by other pars!!!
   sset.insert(p);
if(!JudgeGTHelp(p,cur,sset)) return false;     //Recursion case.
}
return true;
}

bool JudgeGT(GNode *p,unordered_set<GNode*> &sset){
return JudgeGTHelp(p, 0,sset);
}

int main(){
vector<GNode*> vertices;         //include all GNodes in a graph.
unordered_set<GNode*> sset;
GNode * q = vertices[0];
bool res = JudgeGT(q,sset);
if(res==false) cout<<"False"<<endl;
for(int i=0;i<vertices.size();++i){
if(sset.find(vertices[i]) == sset.end()){        //To check for if there exist any other unconnected component!!!
break;
cout<<"False"<<endl;
}
}
cout<<"True, the graph is a tree."<<endl;
getchar();
return 0;
}

No comments:

Post a Comment