Constantly confronted with olympiad problems on graphs, I always wrote a rather long code for implementing DFS, and it took a lot of time to debug it. I wrote constructs like this:
class Graph {
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void DFS(int s, int f);
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
adj[w].push_back(v);
}
void Graph::DFS(int s,int f) {
vector<bool> visited(V, false);
stack<int> stack;
stack.push(s);
while (!stack.empty()) {
s = stack.top();
stack.pop();
if (!visited[s]) {
cout << s << " ";
visited[s] = true;
}
for (list<int>::iterator i = adj[s].begin(); i != adj[s].end(); ++i)
if (!visited[*i])
stack.push(*i);
}
}
It was long and inconvenient, especially when changing one language to another. It is especially difficult when writing from scratch. I need an optimal approach to implement DFS / BFS as briefly and elegantly as possible, preferably in the form of a neat method that takes input values in the form (beginning, end).