fork download
  1. #include <vector>
  2. #include <list>
  3. #include <iostream>
  4.  
  5. class DFS{
  6. private:
  7. struct vertex{
  8. int data;
  9. bool visited;
  10. vertex(int d_=-1, bool v_=false) : data(d_), visited(v_) {}
  11. };
  12. std::vector<std::list<vertex>> G;
  13.  
  14. public:
  15. DFS(int vertices);
  16. vertex addVertex(int data);
  17. void addEdge(int index, int data);
  18. void dfs(int vertex);
  19. void printGraph();
  20. };
  21.  
  22. using namespace std;
  23. DFS:: DFS(int vertices) : G(vertices)
  24. { }
  25.  
  26. DFS::vertex DFS::addVertex(int data)
  27. { return vertex(data, false); }
  28.  
  29. void DFS:: addEdge(int index, int data)
  30. {
  31. size_t gInsert = index;
  32. if ( index >= G.size() )
  33. {
  34. G.push_back(std::list<vertex>());
  35. gInsert = G.size() - 1;
  36. }
  37. G[gInsert].push_back(vertex(data, false));
  38. }
  39.  
  40. void DFS::printGraph()
  41. {
  42. for(size_t i=0; i<G.size(); i++)
  43. {
  44. cout<<"Graph: "<<endl;
  45. std::list<vertex>& ref = G[i];
  46. if ( ref.empty())
  47. cout << "no vertices found";
  48. else
  49. {
  50. auto iter = ref.begin();
  51. while (iter != ref.end())
  52. {
  53. cout << iter->data<<"->";
  54. ++iter;
  55. }
  56. }
  57. cout<<endl;
  58. }
  59. }
  60.  
  61.  
  62. void DFS:: dfs(int vertex){
  63.  
  64. }
  65.  
  66.  
  67. int main(){
  68. DFS dfs(5);
  69. dfs.addEdge(0,1);
  70. dfs.addEdge(0,4);
  71. dfs.addEdge(1,2);
  72. dfs.addEdge(1,3);
  73. dfs.addEdge(1,4);
  74. dfs.addEdge(2,3);
  75. dfs.addEdge(3,4);
  76.  
  77. dfs.printGraph();
  78. return 0;
  79.  
  80. }
  81.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Graph: 
1->4->
Graph: 
2->3->4->
Graph: 
3->
Graph: 
4->
Graph: 
no vertices found