1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
using namespace std;
static int index = 0;
class neighbor
{
public:
int dest ;
int weight;
neighbor( int d= 0, int w= 0)
{
dest = d; weight = w;
}
};
template<typename T>
class vertexInfo
{
public:
enum vertexColor { white , grey , black } ;
typename map< T, int>:: iterator vtxMapLoc;
set<neighbor> edges;
vertexInfo<T>(int index)
{}
vertexInfo<T>( typename map<T, int> :: iterator& iter): vtxMapLoc{iter}
{}
};
template <typename T>
class graph
{
private:
typename map< T, int > :: iterator iter;
map <T,int> vtxMap;
vector<vertexInfo<T> > vInfo;
int numVertices;
int numedges;
stack<int> availStack;
int getvInfoIndex(graph<T>& , const T& v);
public:
void addEdge( graph<T>& , const T& , const T&, int );
set<T> get_Neighbor( graph<T>& , const T& v) ;
void show(graph<T>& );
};
int main()
{
graph<char> g;
char neighbor;
g.addEdge(g,'A','B', 2); // add edge AB of length 2
g.addEdge(g,'A','C', 3);
g.addEdge(g,'B','D', 5);
g.addEdge(g,'C','D', 1);
g.addEdge(g,'B','C', 7);
g.addEdge(g,'D','E', 4);
g.show(g);
cout<<"Enter the node whose Neighbor you want "<<endl;
cin>> neighbor;
set<char> adjVertices = g.get_Neighbor(g, neighbor);
set<char> :: iterator iter;
iter = adjVertices.begin();
while( iter != adjVertices.end())
{
cout<< *iter<< " ";
iter++;
}
return 0;
}
template <typename T>
void graph<T> :: addEdge ( graph<T> & g, const T& v1 , const T& v2, int w)
{
pair <map <char, int> :: iterator, bool> ret ;
ret = g.vtxMap.insert(pair <char, int >( v1, index));
if( ret.second)
{
index++;
g.vInfo.push_back(index);
}
ret = g.vtxMap.insert(pair <char, int >(v2 , index));
if( ret.second)
{
index++;
g.vInfo.push_back(index);
}
}
template<typename T>
set<T> graph<T> :: get_Neighbor( graph<T>& g , const T& v)
{
set<T> adjVertices;
int pos =g.getvInfoIndex(g,v);
const set<neighbor>& edgeSet = g.vInfo[pos].edges;
set<neighbor> :: const_iterator setIter;
int aPos;
for(setIter = edgeSet.begin(); setIter != edgeSet.end(); setIter++ )
{
aPos = (*setIter).dest;
adjVertices.insert((*g.vInfo[aPos].vtxMapLoc).first);
}
return adjVertices;
}
template<typename T>
int graph<T> :: getvInfoIndex( graph<T>& g , const T& v)
{
iter = g.vtxMap.find(v);
int pos = (*iter).second;
cout<< " position is "<< pos<<endl;
return pos;
}
template<typename T>
void graph<T> :: show( graph<T>& g)
{
for( g.iter = g.vtxMap.begin(); g.iter != g.vtxMap.end(); g.iter++)
{
cout<< (*(g.iter)).first <<" - >" << (*(g.iter)).second <<endl;
}
}
|