diff --git a/src/graph.cpp b/src/graph.cpp new file mode 100644 index 0000000..352dc84 --- /dev/null +++ b/src/graph.cpp @@ -0,0 +1,30 @@ +#include +#include + +#include "graph.h" + +using namespace std; + +// Initialize graph +Graph::Graph(int vertices) { + numVertices = vertices; + // Note that this is creating 'vertices' number of lists + adjLists = new list[vertices]; + visited = new bool[vertices]; +} + +// Add edges +void Graph::addEdge(int src, int dest) { adjLists[src].push_front(dest); } + +// DFS algorithm +void Graph::DFS(int vertex) { + visited[vertex] = true; + // Get the list for this particular vertex + list adjList = adjLists[vertex]; + + cout << vertex << " "; + + list::iterator i; + for (i = adjList.begin(); i != adjList.end(); ++i) + if (!visited[*i]) DFS(*i); +} diff --git a/src/graph.h b/src/graph.h new file mode 100644 index 0000000..4b7388c --- /dev/null +++ b/src/graph.h @@ -0,0 +1,16 @@ +#include + +using namespace std; + +class Graph { + int numVertices; + // Adjlist is a list of lists + list* adjLists; + bool* visited; + + public: + Graph(int V); + void addEdge(int src, int dest); + void DFS(int vertex); +}; + diff --git a/src/main.cpp b/src/main.cpp index 11dfb7f..409086a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,64 +2,11 @@ #include #include + +#include "graph.h" + using namespace std; -// Interface for Expr -class Expr { - public: - virtual void print() = 0; -}; - -class BinaryExpr : public Expr { - public: - BinaryExpr(Expr* lhs, Expr* rhs) : lhs(lhs), rhs(rhs) {} - - void print() { - lhs->print(); - rhs->print(); - } - - private: - Expr* lhs; - Expr* rhs; -}; - -class Graph { - int numVertices; - // Adjlist is a list of lists - list* adjLists; - bool* visited; - - public: - Graph(int V); - void addEdge(int src, int dest); - void DFS(int vertex); -}; - -// Initialize graph -Graph::Graph(int vertices) { - numVertices = vertices; - // Note that this is creating 'vertices' number of lists - adjLists = new list[vertices]; - visited = new bool[vertices]; -} - -// Add edges -void Graph::addEdge(int src, int dest) { adjLists[src].push_front(dest); } - -// DFS algorithm -void Graph::DFS(int vertex) { - visited[vertex] = true; - // Get the list for this particular vertex - list adjList = adjLists[vertex]; - - cout << vertex << " "; - - list::iterator i; - for (i = adjList.begin(); i != adjList.end(); ++i) - if (!visited[*i]) DFS(*i); -} - int main() { Graph g(4); g.addEdge(0, 1);