Skip to content

Instantly share code, notes, and snippets.

@TokisakiKurumi2001
Created December 28, 2020 15:15
Show Gist options
  • Select an option

  • Save TokisakiKurumi2001/7d6944da0bb5b9430ff3986c514df8d1 to your computer and use it in GitHub Desktop.

Select an option

Save TokisakiKurumi2001/7d6944da0bb5b9430ff3986c514df8d1 to your computer and use it in GitHub Desktop.
DFS followed Tam's style
#include <stack>
class Graph
{
private:
int V;
Adjacency *adj;
public:
Graph(int V)
{
this->V = V;
adj = new Adjacency[V];
}
void addEdge(int v, int w)
{
adj[v].push(w);
adj[w].push(v);
}
void printGraph()
{
for (int v = 0; v < V; ++v)
{
cout << "\nAdjacency list of vertex " << v << "\nhead ";
adj[v].print();
}
}
Adjacency *DFS(int v)
{
Adjacency * res = new Adjacency(V);
int * visited = new int[V];
for (int i = 0; i < V; i++) {
visited[i] = 0;
}
stack<int> s;
s.push(v);
while (s.size() != 0) {
int u = s.top();
if (visited[u] == 0) {
res->push(u);
visited[u] = 1;
}
s.pop();
int n = adj[u].getSize();
for (int i = n - 1; i >= 0; i--) {
int v = adj[u].getElement(i);
if (visited[v] == 0) {
s.push(v);
}
}
}
delete[] visited;
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment