Splitting code

This commit is contained in:
Imbus 2024-05-27 06:31:02 +02:00
parent 61812932ac
commit 1a89af5189
3 changed files with 49 additions and 56 deletions

30
src/graph.cpp Normal file
View file

@ -0,0 +1,30 @@
#include <iostream>
#include <list>
#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<int>[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<int> adjList = adjLists[vertex];
cout << vertex << " ";
list<int>::iterator i;
for (i = adjList.begin(); i != adjList.end(); ++i)
if (!visited[*i]) DFS(*i);
}

16
src/graph.h Normal file
View file

@ -0,0 +1,16 @@
#include <list>
using namespace std;
class Graph {
int numVertices;
// Adjlist is a list of lists
list<int>* adjLists;
bool* visited;
public:
Graph(int V);
void addEdge(int src, int dest);
void DFS(int vertex);
};

View file

@ -2,64 +2,11 @@
#include <iostream>
#include <list>
#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<int>* 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<int>[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<int> adjList = adjLists[vertex];
cout << vertex << " ";
list<int>::iterator i;
for (i = adjList.begin(); i != adjList.end(); ++i)
if (!visited[*i]) DFS(*i);
}
int main() {
Graph g(4);
g.addEdge(0, 1);